C has the concept of block regions. A variable declared in a given scope has an equivalent lifespan. In the case of a while this means that for each iteration of the loop, there is one variable i . Each time the loop restarts, it creates a new i and sets the value to 1 . i++ only evaluates once on this instance and therefore it will never reach 10 and will indeed be an infinite loop.
The first code example can be fixed by simply moving i to the while loop .
int i = 1; while (true) { printf("This is %d\n" , i); ++i; if(i == 10) break; }
Now i declared in the outer scope and, therefore, for all iterations of the while will be one i .
The for loop case works for the same reason. An iteration variable declared in a for loop is defined once for all iterations of the loop.
source share