Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Today while i was coding , I encounter something which I didn't expect it to happen in this way.Below is just an example code for the problem.

The Code 1

while(true)
{
 int i = 1;

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

The Code 2

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

The Question :

1.)The first code would causes infinite loop while the latter is not.

2.)I don't understand , there's a standard mention variable declare inside while loop can be accessed by any statement inside the while loop , but why the if() can't access the value of variable i while the latter can??

Thanks for spending time reading my question

like image 438
caramel1995 Avatar asked Dec 03 '22 00:12

caramel1995


2 Answers

It's very simple:

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

is equivalent to

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

I.e., the int i = 1 part is executed before the first iteration of the for-loop. for introduces an implicit extra scope block holding any variables declared in the X of for (X;Y;Z).

like image 73
Fred Foo Avatar answered Jan 18 '23 14:01

Fred Foo


C has the notion of block scopes. A variable declared in a given scope has a lifetime equivalent to that scope. In the while loop case that means there is one i variable for every iteration of the loop. Every time the loop restarts it creates a new i and sets it's value to 1. The i++ only evaluates once on that instance and hence it will never reach 10 and will indeed infinite loop.

The first code sample can be fixed by simply moving the i before the while loop.

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

Now i is declared in the outer scope and hence there will be one i for all of the iterations of the while loop.

The for loop case works for nearly the same reason. The iteration variable declared in a for loop is defined once for all iterations of the loop.

like image 28
JaredPar Avatar answered Jan 18 '23 16:01

JaredPar