Search code examples
cloopsfor-loopexecution

Why is the output coming as 8883. How is the code is being executed?


Variable i is becoming 8 at the first entry in loop. Then how the condition i <= 2 satisfied next time?

#include <stdio.h>

int main() 
{
    int i;
    for (i = 0; i <= 2; i++) 
   {
        int i = 8;
        printf("%d", i);
    }
    printf("%d", i);
    return 0;
}

Solution

  • int i=8 is a declaration of a new variable (declares and initializes new variable) which is in a local scope that shadows the existing variable from the more general scope.

    In other words:

    1. First int i defines variable;
    2. for uses that variable and initializes it with 0 and starts a cycle;
    3. int i=8 - as it is written with int - defines new local variable that because it has the same name that i from outer scope - shadows it ("shadowing" is a term). And so further code in the loop uses new local i which set to 8.
    4. Internal printf("%d",i); prints 8.
    5. Cycle ends and local scope gets erased, and so that internal i=8 erased also.
    6. for lives outside (in more general scope) of the scope of the loop. for condition uses variable from outside, which was set to i=0 in step #2. So for in a second cycle instructed to increment (i++) it, so i=1, which passes the i <= 2 check. So for indeed starts executing next cycle of internal code.
    7. Inside for loop external i gets shadowed by internal int i=8... (step #3).

    In short: It is because code declares a new variable with int i.

    The good style is to: for(int i=0;i<=2;i++) - always declare and initialize the variable in one instruction.