views:

66

answers:

2

Look at this example:

int i;
for (i=1;i.......

and this:

for (int i=1;i........

What's the difference between them?

+11  A: 

The first one declares the variable in the scope outside of the loop; after the loop has ended, the variable will still exist and be usable. The second one declares the variable such that it belongs to the scope of the loop; after the loop, the variable ceases to exist, preventing the variable from being inadvertantly/mistakenly used.

In C99, C++, Java, and other similar languages, you will find mostly the second syntax as it is safer -- the loop index belongs to the loop and isn't modified / shared elsewhere. However, you will see a lot of the former in older C code, as ANSI C did not allow the loop variable to be declared in the loop like that.

To give an example:

int i;
// ... lots of stuff
for ( i = 0; i < 5; i++ ){
    printf("%d\n",i); // can access i; prints value of i
}
printf("%d\n",i); // can access i; prints 5

By contrast:

for (int i = 0; i < 5; i++ ){
    std::cout << i << std::endl; // can access i; prints value of i
}
std::cout << i << std::endl; // compiler error... i not in this scope
Michael Aaron Safyan
thanks Michael the answer was really informative.
Ehsan Mamakani
+2  A: 

That would depend on the language, which you haven't specified :-)

In C (and some others), the scope (effectively duration in this case) of the variable is different. In the first, the variable exists after the loop because it's declared outside it.

In the latter, it disappears when the loop ends because its existence is "inside" the loop body.

paxdiablo
thanks for the answer paxdiablo.
Ehsan Mamakani