Reputation: 423
Why is the postfix increment operator (++) executed after the assignment (=) operator in the following example? According to the precedence/priority lists for operators ++ has higher priority than = and should therefore be executed first.
int a,b;
b = 2;
a = b++;
printf("%d\n",a);
will output a = 2.
PS: I know the difference between ++b and b++ in principle, but just looking at the operator priorities these precende list tells us something different, namely that ++ should be executed before =
Upvotes: 2
Views: 214
Reputation: 4873
++
is evaluated first. It is post-increment, meaning it evaluates to the value stored and then increments. Any operator on the right side of an assignment expression (except for the comma operator) is evaluated before the assignment itself.
Upvotes: 7
Reputation: 213842
Operator precedence and order of evaluation of operands are rather advanced topics in C, because there exists many operators that have their own special cases specified.
Postfix ++ is one such special case, specified by the standard in the following manner (6.5.2.4):
The value computation of the result is sequenced before the side effect of updating the stored value of the operand.
It means that the compiler will translate the line a = b++;
into something like this:
b
into a CPU register. ("value computation of the result")b
. ("updating the stored value")a
.This is what makes postfix ++ different from prefix ++.
Upvotes: 2
Reputation: 16496
The increment operators do two things: add +1 to a number and return a value. The difference between post-increment and pre-increment is the order of these two steps. So the increment actually is executed first and the assignment later in any case.
Upvotes: 0
Reputation: 234715
It is. It's just that, conceptually at least, ++
happens after the entire expression a = b++
(which is an expression with value a
) is evaluated.
Upvotes: 3