zzzbbx
zzzbbx

Reputation: 10161

while infinite loop?

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?

Upvotes: 0

Views: 719

Answers (2)

mjsr
mjsr

Reputation: 7590

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

Upvotes: 0

BlackBear
BlackBear

Reputation: 22989

x = x++;

is undefined behavior

Upvotes: 14

Related Questions