In the C programming language, an expression is evaluated based on the operator precedence and associativity. When there are multiple operators in an expression, they are evaluated according to their precedence and associativity. The operator with higher precedence is evaluated first and the operator with the least precedence is evaluated last.
Operator precedence is used to determine the order of operators evaluated in an expression. In c programming language every operator has precedence (priority). When there is more than one operator in an expression the operator with higher precedence is evaluated first and the operator with the least precedence is evaluated last.
Operator associativity is used to determine the order of operators with equal precedence evaluated in an expression. In the c programming language, when an expression contains multiple operators with equal precedence, we use associativity to determine the order of evaluation of those operators.
Precedence | Operator | Operator Meaning | Associativity |
1 | () [] → . |
function call array reference structure member access structure member access |
Left to Right |
2 | ! ~ + - ++ -- & * sizeof (type) |
negation 1's complement Unary plus Unary minus increment operator decrement operator address of operator pointer returns size of a variable type conversion |
Right to Left |
3 | * / % |
multiplication division remainder |
Left to Right |
4 | + - |
addition subtraction |
Left to Right |
5 | << >> |
left shift right shift |
Left to Right |
6 | < <= > >= |
less than less than or equal to greater than greater than or equal to |
Left to Right |
7 | == != |
equal to not equal to |
Left to Right |
8 | & | bitwise AND | Left to Right |
9 | ^ | bitwise EXCLUSIVE OR | Left to Right |
10 | | | bitwise OR | Left to Right |
11 | && | logical AND | Left to Right |
12 | || | logical OR | Left to Right |
13 | ?: | conditional operator | Left to Right |
14 | = *= /= %= += -= &= ^= |= <<= >>= |
assignment assign multiplication assign division assign remainder assign addition assign subtraction assign bitwise AND assign bitwise XOR assign bitwise OR assign left shift assign right shift |
Right to Left |
15 | , | separator | Left to Right |
To understand expression evaluation in c, let us consider the following simple example expression...
6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)
Evaluation of expression | Description of each operation |
6*2/( 2+ 1 * 2 /3 +6) +8 * (8/4) | An expression is given. |
6*2/(2+2/3 + 6) + 8 * (8/4) | 1 is multiplied by 2, giving value 2. |
6*2/(2+0+6) + 8 * (8/4) | 2 is divided by 3, giving value 0. |
6*2/ 8+ 8 * (8/4) | 2 is added to 6, giving value 8. |
6*2/8 + 8 * 2 | 8 is divided by 4, giving value 2. |
12/8 +8 * 2 | 6 is multiplied by 2, giving value 12. |
1 + 8 * 2 | 12 is divided by 8, giving value 1. |
1 + 16 | 8 is multiplied by 2, giving value 16. |
17 | 1 is added to 16, giving value 17. |