C programming - associativity of operators
The associativity of operators in C programming determines the order in which operators with the same precedence are evaluated in an expression. In other words, it specifies whether the operators are evaluated from left to right or from right to left.
The following operators are left associative, which means that they are evaluated from left to right:
- Assignment operators
=
,+=
,-=
and so on - Relational operators
<
,<=
,>
, and>=
- Equality operators
==
and!=
- Bitwise shift operators
<<
and>>
- Addition
+
and subtraction-
- Multiplication
*
, division/
, and modulo%
- Bitwise AND
&
- Bitwise XOR
^
- Bitwise OR
|
- Logical AND
&&
- Logical OR
||
On the other hand, the following operators are right associative, which means that they are evaluated from right to left:
- Unary operators
++
,--
,+
,-
,!
, and~
- Ternary conditional operator
?:
Note that the parentheses ()
have no associativity, as they group the operators in the order we want them to be evaluated.
Understanding the associativity of operators is important in cases where an expression contains multiple operators with the same precedence, as it determines the order in which they are evaluated. If the associativity is left-to-right, the leftmost operator is evaluated first, while if the associativity is right-to-left, the rightmost operator is evaluated first.