Operator Precedence in C

Ambiguity can arise when combining operators. Parenthesis are recommended for making an expression unambiguous, but what happens, for instance, when we have:

x = 2 + 3 * 4;

or even worse:

int x=2;

int y=5;

int z = x+++y;

cout << x << " "

<< y << " "

<< z << endl;

Should the "x+++y" be interpreted as "(x++) + y" or as "x + (++y)"? Note that in both cases the value 8 will be stored in z, but in "(x++) + y" x is changed, while in "x + (++y)" y is changed instead. Here is a precedence chart (note that we haven't yet seen many of the operators shown below):

Operators Associativity Description

() [] -> . ++ -- Left to right Postfix ++ and --

! ++ -- + - * & (type) sizeof

Right to left Unary +, -, and *; Prefix ++ and --

* / % Left to right Multiplicative

+ - Left to right Binary +, -

<< >> Left to right Shift binary numbers

< <= > >= Left to right Relational

== != Left to right Equality / Inequality

& Left to right Bitwise and

^ Left to right Bitwise xor

| Left to right Bitwise or

&& Left to right Logical and

|| Left to right Logical or

?: Left to right Conditional (ternary)

= += -= *= /= %= &= ^= |= <<= >>=

Right to left Assignment

, Left to right Sequential evaluation

It is highly recommended that you use parentheses to disambiguate your expressions.