Can anyone explain the output of the following piece of code in C:
void main( )
{int a=1, b;
b=(++a)+(++a);
printf("a=%d, b=%d", a, b);
}
Output:
a=3, b=6
Can anyone explain why b=6 here and NOT 5 as expected.
Mark Holland - 09 Apr 2007 11:42 GMT
> Can anyone explain the output of the following piece of code in C:
>
[quoted text clipped - 8 lines]
>
> Can anyone explain why b=6 here and NOT 5 as expected.
You are modifying the value of a variable (in this case a) twice
between sequence points. According to the C++ standard this is
undefined behaviour, meaning anything can happen. (i.e. Your program
is invalid). Hence you get those "unexpected" results.
http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.15
However, one does wonder why you are posting to a Java newsgroup with
this topic? Are you trying to contrast this behaviour with Java? In
which case it is worth noting that this behaviour is indeed specified
in Java and produces the expected value of 5.
Mark
Patricia Shanahan - 09 Apr 2007 11:47 GMT
> Can anyone explain the output of the following piece of code in C:
>
[quoted text clipped - 8 lines]
>
> Can anyone explain why b=6 here and NOT 5 as expected.
If I were writing in a C newsgroup, I don't think would not have any
particular expectation for the result of b=(++a)+(++a).
Patricia