Re: Varied results for ++ operator in VC++/Unix.

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

adebaene_at_club-internet.fr
Date: 01/21/05


Date: 21 Jan 2005 04:42:32 -0800


krishna wrote:
> I executed a program containing the following piece of code and got
the
> results as below
> Code
> ------
> #include "stdio.h"
>
> int main()
> {
> int a = 1;
> printf("the val is %d\n", ++a + ++a );
> }

You are invoking undefined behaviour, because the expression "++a +
++a" does not contain any sequence point. More precisely : there is no
guarantee that the side-effect of the first "++a" (ie, incrementing a)
has been applied when the second "++a" is evaluated. With respect to
C++ standard, the behaviour is undefined, so both answers are equelly
correct.
This is stated in 5,4 in the C++ standard : "Between the previous and
next sequence point a scalar object shall have its stored value
modified at most once by the evaluation of an expression".
Arnaud
MVP - VC



Relevant Pages

  • Re: C Test Incorrectly Uses printf() - Please Confirm
    ... With a function call, the arguments can be N branches at the branch-point, and they are all grouped together for theoretically simultaneous evaluation. ... It should be clear that the sequence points were never disputed as being critical to the discussion. ... which details a requirement for strict evaluation according the semantics. ... volatile int i; ...
    (comp.lang.c)
  • Re: Knowing your sequence points
    ... > int main ... "Between the previous and next sequence point an object shall have its ... stored value modified at most once by the evaluation of an expression. ... If just so happens that if your compiler evaluates the subexpression ...
    (comp.lang.c)
  • Re: Sub-sub-expression evaluation order
    ... > anything in the standard that says that it must complete (ignoring side- ... The evaluation can be implemented in any way, ... There are indeed sequence points at the beginning of each function's ... requirements of the standard and the code produces undefined behavior. ...
    (comp.lang.c)
  • Re: Knowing your sequence points
    ... >> int main ... > stored value modified at most once by the evaluation of an expression. ... But the '+ n' subexpression attempts to access the prior value ... Only sequence points impose an order of evaluation. ...
    (comp.lang.c)
  • Re: Yet Another Spinoza Challenge
    ... int getc ... Between the previous and next sequence point an object shall have ... its stored value modified at most once by the evaluation of an ... the prior value shall be read only to ...
    (comp.lang.c)