Reputation: 3591
This is a beginners question.
Following is the C++ code that I was working with
int main() {
int x=5, y=5;
cout<<x--;
cout<<",";
cout<<--x;
cout<<",";
cout<<y--<<","<<--y;
return 0;
}
When run in Turbo C++ 3.0 the following is the output displayed by the code:
5,3,4,4
When compiled with Code::Blocks on Windows (uses MinGW with GCC/G++) the following is the output displayed:
5,3,4,3
Previously, I have heard that sometimes different compilers behave differently to certain problems, but I don't understand why this result is being displayed. Since logically, as I think, the output should be:
5,3,5,3
Can you please tell me the reason for such output logically.
Thank you!
Upvotes: 1
Views: 320
Reputation: 55425
There is no right or wrong output. Your code has undefined behavior and anything is possible.
The reason lies in paragraph 1.9.15 (n3337) of C++ standard (emphasis mine):
Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [Note: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations. —end note ] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.
In this line
cout << y-- << "," << --y;
you've introduced two side effects (increments by postfix and prefix, respectively) and two value computations (results of y--
and --y
) on a scalar object (y
) where they are unsequenced. Thus, your program is ill-formed and just about anything is a possible output.
Read more about this here.
Upvotes: 3
Reputation: 42594
cout<<y--<<","<<--y;
is an expression with two unsequenced side effects on y
, and therefore has undefined behavior.
Upvotes: 0