+ 2
Could the use of the same variable name inside and outside the loop result in shadow variables ?
14 odpowiedzi
+ 2
Sanjay Kamath
just don't use
for(i =0;i<5;i++)
because it will mess up the outside variable i
use instead
for(int i=0;i<5;i++)
so that the i in the for block is different from the i outside
+ 4
i was declared before the for loop, so nothing shadows it. if you wrote
for (int i=0; i<5; i++)
the new i would outshadow ths previous one, but only in scope of the curly brackets after for
+ 3
What do you mean by "shadow variables" ?
+ 3
//Example for shadowing :
// local variables are always pointed first. so it shadows same named global variables..
#include <stdio.h>
int main(){
int i = 9;
for (int i=0;i<5;i++)
printf("inside i %d\n",i);
printf("outside i %d\n",i);
}
+ 2
Local variables shadows to their global variables.
+ 2
Bob_Li Sir, the original problem is as described in the question.., which means that shadowing exists.
+ 2
Sanjay Kamath i outside braces is undefined, and it is initialized inside the for loop - in the conditions section before the first ;. then it is modified after the last ; in the same section - it gets repeatedly increased by 1, so finally it equals to 5, the result
+ 2
Sanjay Kamath
it just means you did not redefine the variable i in your for loop, which is what you normally should do. That is why the outside variable i was used, and you get the result you are getting.
+ 1
Patrick exactly.... then how do you explain the result ?
I outside the braces is 0.
+ 1
Arsenic : Same variable name inside and outside the loop
+ 1
https://en.m.wikipedia.org/wiki/Variable_shadowing
As a standard it's not advisable to use this feature....
0
yes
0
int i;
int main()
{
for (int i=1;i<=4;i++)
cout<<setw(3)<<i<<endl;
return 0;
}
0
This was from the test battery 🔋.