Re: increasing var twice in a statement

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Christian Böhme wrote:
chris@xxxxxxxxxxxxxxxxxxxx wrote:

I feel 10 is the correct answer due to the pre-increment operator having a
higher precedence than the addition operator. This would mean both
increments will be done before the addition (creating 5 + 5).

That's interesting.  With b having been initialized to 3 but ending
up at 5 on _both_ sides of "+" would imply that b was then incremented
_four_ times (which is clarly not what the semantics of the statement
are).

I suspect a 10 to be the result of overly "smart" playing with the
operands of the addition on the compiler's part: b is expected to
be incremented twice as it must be evaluated twice according to
the definition of the addition operation.  However, the compiler
also recognizes that the expression "++b" as operand to the "+"
operator appears twice which it transforms into a multiplication
of the addition's operand and 2.  Remember also that addition is
a commutative operation which means it is irrelevant in which order
its operands are evaluated to produce the result.


My reasoning was as follows:

1) The statement was a = ++b + ++b;
2) b=3 before this statement
3) The operator ++ on the right hand side of the + operator is executed first by rules of precedence. As it is pre-increment, b becomes 4. 4)The operator ++ on the left hand side of the + operator is then executed. As it is also pre-increment, b is again altered to become 5.
5) Then the operator + is executing adding b (now 5) to b (still 5).

That's only two increments of b, but both before the addition operator.

Chris


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux