Catalin Ghita
Catalin Ghita

Reputation: 826

C order of operations?

Can someone please explain me why the result of the following code is 9? I am really confused..

#include <stdio.h>

int main (void)
{ 
   int a = 3, rez;
   rez = a-- + (-3) * (-2);

   return 0;
}

Upvotes: 1

Views: 1045

Answers (1)

John Bode
John Bode

Reputation: 123578

The expression

rez = a-- + (-3) * (-2)

is parsed as

res = ((a--) + ((-3) * (-2)))

and is evaluated as "the result of a-- is added to the result of (-3) * (-2), and the final result is assigned to res".

Postfix -- has higher precedence than unary -, which has higher precedence than binary *, which has higher precedence than binary +, which has higher precedence than =.

Note that precedence and order of evaluation are not the same thing - it's not guaranteed that a-- is evaluated before (-3) * (-2), or that -3 is evaluated before -2; all that's guaranteed is that the result of (-3) * (-2) is known before it can be added to the result of a--.

Futhermore, the side effect of a-- doesn't have to be applied immediately after evaluation. This means that the following is a perfectly valid order of operations:

t1 = a
t2 = -2
t2 = t2 * -3
res = t1 + t2
a = a - 1

Upvotes: 5

Related Questions