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
In your second code snippet, the int r = r * x;
declares a new variable called r
that exists only for the duration of each iteration of the for
loop. Further, this declaration hides (or shadows) the earlier variable of the same name from the scope of that loop - so any changes made to r
in the loop do not affect the 'original' r
variable.
Enabling compiler warnings will generally reveal such problems. For example, for your second code snippet, the clang-cl compiler gives this:
warning : declaration shadows a local variable [-Wshadow]
Because the 'scope' of r in the second code is inside the loop, when you leave the loop the variable is not longer valid.
for (k = 1; k <= y; k++)
{
int r = r * x; //here you create the variable
} //here it is destroyed
In c/c++ the variables are local to a scope, when you leave the scope you loose the variable. Everything inside {} is a scope (internal to the outside scope). Inside scopes can see variables of outside scope.
void func()
{ // begin scope of a function
// can't see any variables defined inside the scope of the while
// they don't exists yet
while ()
{ // begin scope of a while
// can see variables defined inside the scope of the function
}
// can't see any variables defined inside the scope of the while
// they don't exists anymore
}
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.For the first piece of code, r = r * x
refers to the r
defined outside the for loop, which means it works as expected. For the second piece of code, when you do int r = r * x
, you're declaring another r
scoped to the for loop, and the changes are not reflected in the outer r
. Then, outside the for loop, you switch back to the outer r
, which is still 1.