increasing var twice in a statement

me22 me22.ca@gmail.com
Fri Jun 15 20:31:00 GMT 2007


On 15/06/07, Willi Mann <willi@wm1.at> wrote:
> int main(void) {
>         int a;
>         int b;
>         b = 3;
>         a = ++b + ++b;
>         printf("%d\n",a);
>         return 0;
> }
>
> I would have expected 9, but gcc 4.1.2 produced a binary that wrote 10.
>
Getting an 8 would also be perfectly reasonable, based on the
side-effect definition of pre-increment.

If it were not undefined,
a = ++b + ++b;
would be equivalent to
a = (b+1) + (b+1);
with 2 side-effects of
b = b+1;
occuring some point before the sequence point and after the evaluation
of the respective b.

But because of those side effects, the behaviour is undefined, as has
been mentioned.  Maybe you'll get lucky and the compiler will start
Nethack for you. ;)

~ Scott



More information about the Gcc-help mailing list