0

I came across this question in this forum

#include <iostream>

using namespace std;

int main(int argc, char** argv) {

    int x=0;
    while (x<3) {
        x = x++;
        cout << x << endl;
    }

    return 0;
}

given the code above, why is the while loop infinite? Using gcc 4.4 under mac os, the while loop does terminate :) so the question does not apply for all architectures. The output I get tough is
1
2
3

I don't see 0, and I guess the reason is related to the double assignment?

4
  • 6
    Undefined Behavior is Undefined Commented Mar 16, 2011 at 21:36
  • on which platform it's infinite? or should I say compiler. Commented Mar 16, 2011 at 21:42
  • 1
    @Piotr: The one he mentions in the question. Commented Mar 16, 2011 at 21:45
  • under mac osx x64 (gcc 4.4) the loop does terminate. Apparently, using some other compilers and/or platform it may be infinite programmers.stackexchange.com/questions/25836/… Commented Mar 16, 2011 at 22:46

2 Answers 2

14
x = x++;

is undefined behavior

Sign up to request clarification or add additional context in comments.

12 Comments

Which means that the loop is neither infinite nor finite?
@John: this means we cannot say why the program behaves this or that way
@John: Which means that the program is invalid, and anyting can happen.
And note that really means anything. It could be that x winds up at the old value, or the new value, or some completely different value, or the program could crash, or the program could start nethack, or demons could come flying out of your nose.
|
0

you never see zero because the increment is before the cout.

2 Comments

It is undefined behavior because the value of x is set twice between sequence points. The compiler is free to do the assignment and increment in any order, or really to do anything else that might make sense to it.
i think different but im going to read further in the c++ manual that i have. Long time ago i learn that the POSTIncrement like this x=a++; means x=a; a=a+1; i dont get whay in this situation where a=x is differen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.