I am confused about the output of this code:
int c=3;
cout<<(c++)*(c++);
I use gcc and the output is 9
, but someone said that it's undefined behavior, why?
The issue is "Sequence points":
http://en.wikipedia.org/wiki/Sequence_point
A sequence point in imperative programming defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed.
Sequence points also come into play when the same variable is modified more than once within a single expression. An often-cited example is the C expression i=i++, which apparently both assigns i its previous value and increments i. The final value of i is ambiguous, because, depending on the order of expression evaluation, the increment may occur before, after, or interleaved with the assignment. The definition of a particular language might specify one of the possible behaviors or simply say the behavior is undefined. In C and C++, evaluating such an expression yields undefined behavior.[1]
As it happens, I get exactly the same answer - "9" - on both MSVC (Windows) and gcc (Linux). I also get a warning whether I compile with gcc ("C") or g++ (C++):
$ g++ -o tmp -Wall -pedantic tmp.cpp
tmp.cpp: In function "main(int, char**)":
tmp.cpp:7: warning: operation on "c" may be undefined
$ ./tmp
c=9...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With