1

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!

Chetan Bhasin
  • 3,503
  • 1
  • 23
  • 36
  • possible duplicate of [Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc...)](http://stackoverflow.com/questions/949433/could-anyone-explain-these-undefined-behaviors-i-i-i-i-i-etc) – Casey Jul 21 '13 at 13:21
  • @Casey thanks for pointing me to that question. I didn't find it in search results, but it did explained a lot. – Chetan Bhasin Jul 21 '13 at 13:55
  • Turbo C++ 3.0 was released in 1991, so it couldn't possibly have been a C99 compiler. – Spire Jul 21 '13 at 19:23
  • @Spire thanks for telling. I'll update the question description. – Chetan Bhasin Jul 22 '13 at 09:46

2 Answers2

3

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.

Community
  • 1
  • 1
jrok
  • 54,456
  • 9
  • 109
  • 141
0

cout<<y--<<","<<--y; is an expression with two unsequenced side effects on y, and therefore has undefined behavior.

Casey
  • 41,449
  • 7
  • 95
  • 125