Operator precedence and associativity are two important concepts in C language that dictate the order in which operators are evaluated in expressions.
Operator Precedence:
Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first. For example, in the expression a + b * c
, multiplication (*
) has higher precedence than addition (+
), so b * c
is evaluated first.
Here is a brief summary of operator precedence in C, from highest to lowest:
- Postfix operators:
() [] -> . ++ --
- Unary operators:
+ - ! ~ ++ --
- Multiplicative operators:
* / %
- Additive operators:
+ -
- Shift operators:
<< >>
- Relational operators:
< <= > >=
- Equality operators:
== !=
- Bitwise AND operator:
&
- Bitwise XOR operator:
^
- Bitwise OR operator:
|
- Logical AND operator:
&&
- Logical OR operator:
||
- Conditional operator:
? :
- Assignment operators:
= += -= *= /= %= &= ^= |= <<= >>=
- Comma operator:
,
We can use parentheses to override the default precedence and explicitly specify the order of evaluation.
Operator Associativity:
Operator associativity defines the direction in which operators with the same precedence are grouped. It can be left-to-right or right-to-left.
Left-to-Right Associativity: Operators are evaluated from left to right when they have the same precedence. Most operators in C, like addition (
+
), multiplication (*
), and assignment (=
), have left-to-right associativity.Example:
a + b + c
is equivalent to(a + b) + c
.Right-to-Left Associativity: Operators are evaluated from right to left when they have the same precedence. Unary operators, such as the post-increment operator (
a++
), have right-to-left associativity.Example:
a++
is equivalent toa = a + 1
.
Understanding operator precedence and associativity is crucial for writing correct and predictable expressions in C. It helps avoid ambiguities in expressions and ensures that the code behaves as expected.