What is the difference between a variable declaration in a loop and before a loop?

Take a look at this example:

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

and this:

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

What is the difference between the two?

+3
source share
2 answers

The first declares a variable in an area outside the loop; after the loop ends, the variable will still exist and be used. The second declares the variable in such a way that it belongs to the scope of the loop; after the loop, the variable ceases to exist, preventing accidental / erroneous use of the variable.

C99, ++, Java , . / . , C-, ANSI C .

:

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

:

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
+10

, : -)

C ( ) ( ) . , ​​ .

, , "" .

+2

Source: https://habr.com/ru/post/1743480/


All Articles