Why the output is different when we add 'int' tag twice in a program when using 'for' loop?

前端 未结 4 811
滥情空心
滥情空心 2021-01-15 12:26

I am a learner and new to C language. While I was creating a function which will give power of two numbers using for loop I encounter that using int declaration before loop

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-15 12:54

    for (k = 1; k <= y; k++)
    {
       int r = r * x;
    }
    

    int r inside of the for loop declares a separate and unique variable which only is visible in the scope of the for loop.

    This r doesn't refer to the r outside of the for loop.

    But inside of the initialization part of the loop's (inner) r, the inner r doesn't shadow the outer r because the declaration of the inner r isn't fulfilled at this moment of time.

    So, the r in r * x refers to the outer r, not the inner one.

    Had you wrote:

    for (k = 1; k <= y; k++)
    {
       int r = 2; 
       r = r * x;
    }
    

    then all r's would refer to the inner r and would completely shadow the outer one.


    Thereafter, When you use

    printf("Power is %d", r);
    

    it prints the value for the outer r variable, which remains unchanged. This is proven with the output of

    Power is 1
    

    Side Note:

    • It doesn't really much sense to declare variables inside of loop's body as you instruct to declare a new variable at each iteration. A compiler can optimize this to only one definition, but better place declarations inside of the initialization part of the for loop or declare them before the loop.

提交回复
热议问题