Operators
C has a rich set of operators. Things can get very complicated
with C's various often compact ways of giving expressions.
Unary operators
sizeof(i) the number of bytes of storage allocated to i
+1 positive 1
-1 negative 1
~i one's complement (bitwise complement)
!i logical negation (i.e., 1 if i is zero, 0 otherwise)
*i returns the value stored at the address pointed to by i
&i returns the address in memory of i
++i adds one to i, and returns the new value of i
--i subtracts one from i, and returns the new value of i
i++ adds one to i, and returns the old value of i
i-- subtracts one from i, and returns the old value of i
i[j] array indexing
i(j) calling the function i with argument j
i.j returns member j of structure i
i->j returns member j of structure pointed to by i
a,b evaluate both a and b, return the value of b
Binary operators
+ addition
- subtraction
* multiplication
/ division
% remainder
% modulo
<< left-shift
>> right-shift
& bitwise AND
| bitwise OR
^ bitwise exclusive-OR
&& logical AND
|| logical OR
< less than
> greater
> than
<= less than or equal
>= greater than or equal
== equals
!= does not equal
Note:
- C has no keywords as true or false. They are non-zero or zero values,
usually 1 or 0.
- `OR', `AND' , and `NOT': differences between bitwise and logical operators.
Assignment operators
= assignment
+= addition assignment
-= subtraction assignment
*= multiplication assignment
/= division assignment
%= remainder/modulus assignment
&= bitwise AND assignment
|= bitwise OR assignment
^= bitwise exclusive OR assignment
<<= left shift assignment
>>= right shift assignment
- Assignment operators takes the value on the right and
places it into the variable on the left.
- C provides more derivatives by combining computation and assignment together
- Note the difference between assignment and equal operators.
Don't make the mistake of using '=' when you meant '=='!
Precedence and Associativity
Operator Associativity
-------- -------------
() [] ->> . left-to-right
- + ++ -- ! ~ * & sizeof (type) right-to-left
* / % left-to-right
+ - left-to-right
<< >> left-to-right
< <= > >= left-to-right
== != left-to-right
& left-to-right
^ left-to-right
| left-to-right
&& left-to-right
|| left-to-right
?: right-to-left
= += -= *= /= %= &= ^= |= <<= >>= right-to-left
, left-to-right
- Precedence: The order in which operators
are applied in expressions.
- Associativity: The order in which expressions involving operators
of the same precedence are evaluated.
- Use parentheses to specify a different order of evaluation.
It is recommended to use parentheses for clear and easy to read programs.
But you still need to be prepared for the complexity in general.
Samples:
int a, b, c;
a = 2, b = 1;
c = 1 + a - -- b;
c = 1 + a - b -- ;
c = 1 + a - ++ b;
c = 1 + a - b ++ ;
c = (1 + a, b);
c = 1 + (a, b);