Confuse with a variable scope for while and for loop (C programming)

Today, when I was coding, I came across something that I did not expect that to happen this way. The following is sample code for the problem.

Code 1

while(true) { int i = 1; printf("This is %d\n" , i); ++i; if(i == 10) break; } 

Code 2

 for(int i = 1 ; ; i++) { printf("This is %d\n" , i); if(i == 10) break; } 

Question:

1.) The first code will cause an infinite loop, and the last will not.

2.) I don’t understand if there is a standard mention variable inside the while loop that can be accessed by any operator inside the while loop, but why if() cannot access the value of the variable i, while the latter can ??

Thanks for taking the time to my question.

+4
source share
3 answers

It is very simple:

 for(int i = 1 ; ; i++) { printf("This is %d\n" , i); if (i == 10) break; } 

equivalently

 { int i = 1; while (true) { printf("This is %d\n" , i); if (i == 10) break; i++; } } 

Ie, the int i = 1 is executed before the first iteration of for -loop. for introduces an implicit block of additional scopes containing any variables declared in X of for (X;Y;Z) .

+11
source

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.

+6
source

The problem is that in your while loop you not only declare i, you initialize it. Therefore, at each iteration of the loop, I am reset to 1, causing an infinite loop.

The for loop initializes i = 1 first before starting the loop, so this is more like writing a while loop as follows:

 int i = 1; while (true) { printf("This is %d\n" , i); if (i == 10) break; i++; } 
+1
source

All Articles