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
It’s very simple:
is equivalent to
I.e., the
int i = 1part is executed before the first iteration of thefor-loop.forintroduces an implicit extra scope block holding any variables declared in theXoffor (X;Y;Z).