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
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:
for
loop or declare them before the loop.