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
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
}