Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does For-Loop counter stay?

Simple Question. Imagine this in ANSI-C:

int i;

for(i=0 ; i<5 ; i++){
   //Something...
}

printf("i is %d\n", i);

Will this output "i is 5" ?

Is i preserved or is the value of i undefined after the loop?

like image 554
Bigbohne Avatar asked Dec 01 '10 11:12

Bigbohne


2 Answers

Yes. If i is declared outside of the for loop it remains in scope after the loop exits. It retains whatever value it had at the point the loop exited.

If you declatred I in the loop:

for (int i = 0 ; i < 5 ; i++)
{

}

Then i is undefined after the loop exit.

like image 137
PaulJWilliams Avatar answered Sep 25 '22 19:09

PaulJWilliams


Variable i is defined outside of the scope of the loop (which is great, or you wouldn't be able to print it in that case).

And it is post-icnremented for every-turn of the loop, for which the end condition is "stop when i is bigger or equal to 5".

So it really makes perfect sense for i to be equal to 5 at this point.

A block scope is not exactly the same as a function scope in C. The variable i doesn't "get back" magically to its previous value when you step out of the loop's scope.

like image 29
haylem Avatar answered Sep 25 '22 19:09

haylem