0

Why this code gives infinite loop ?

int i=0; while(i<=5){ printf("*"); i=i++; } https://code.sololearn.com/c812sBYy2WvG/?ref=app Ps: I am using gcc compiler. https://code.sololearn.com/c812sBYy2WvG/?ref=app

7th Oct 2019, 8:14 AM
Himanshu Kumar
Himanshu Kumar - avatar
3 odpowiedzi
+ 2
As Schindlabua and Chirag Kumar said, because the C++ standard doesn't specify the exact order of evaluation, the order is unspecified and is compiler implementation dependant. My guess is that `i` is pre-incremented first, and the old value of `i` returned by `i++` is assigned to `i`. Example: int i = 0; i = i++; Step 1: i = [i++], i++ => int temp; temp = i; i = i + 1; return temp; // returns 0 Step 2: i is now 1, but i is assigned to the old value of i, i = 0 Step 3: Rinse and repeat.
7th Oct 2019, 8:40 AM
jtrh
jtrh - avatar
+ 1
You don't need to assign here. This is enough: printf("*"); i++; because `i++` is shorthand for `i = i + 1`! When you do `i=i++` it is actually undefined behaviour and anything can happen. Maybe it will run forever, maybe not.
7th Oct 2019, 8:24 AM
Schindlabua
Schindlabua - avatar
+ 1
It's unexplainable C compiler himself can't explain why is this code giving infinite loop. So you can just use i++; instead of i=i++;
7th Oct 2019, 8:28 AM
Chirag Kumar
Chirag Kumar - avatar