Search code examples
cfor-loopvar

defining a var in loop


What is difference between defining a var inside a loop or outside? for example:

int a;
for(int i=1; i<11; i++){
    a = rand()%10;
    printf("%d\n",a);
}

the a is defined first and then is used in loop. but in :

for(int i=1; i<11; i++){
    int a = rand()%10;
    printf("%d\n",a);
}

here a is defined in the loop. What is difference and which one is slower?


Solution

  • the difference is the scope of the variable. a exists after the loop ends in the 1st case, but does not in the 2nd case.