increasing var twice in a statement

Christian Böhme monodhs@gmx.de
Fri Jun 15 19:52:00 GMT 2007


chris@blueband.demon.co.uk 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.


Cheers,
Christian



More information about the Gcc-help mailing list