+ 2

Could the use of the same variable name inside and outside the loop result in shadow variables ?

https://code.sololearn.com/c68B5v700VAz/?ref=app

2nd Sep 2022, 2:21 PM
Sanjay Kamath
Sanjay Kamath - avatar
14 Respuestas
+ 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
3rd Sep 2022, 10:47 AM
Bob_Li
Bob_Li - avatar
+ 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
3rd Sep 2022, 1:04 AM
Patrick
Patrick - avatar
+ 3
What do you mean by "shadow variables" ?
2nd Sep 2022, 2:25 PM
Arsenic
Arsenic - avatar
+ 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); }
3rd Sep 2022, 8:48 AM
Jayakrishna 🇮🇳
+ 2
Local variables shadows to their global variables.
2nd Sep 2022, 3:21 PM
Jayakrishna 🇮🇳
+ 2
Bob_Li Sir, the original problem is as described in the question.., which means that shadowing exists.
3rd Sep 2022, 1:00 PM
Sanjay Kamath
Sanjay Kamath - avatar
+ 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
3rd Sep 2022, 1:42 PM
Patrick
Patrick - avatar
+ 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.
3rd Sep 2022, 3:06 PM
Bob_Li
Bob_Li - avatar
+ 1
Patrick exactly.... then how do you explain the result ? I outside the braces is 0.
3rd Sep 2022, 2:43 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 1
Arsenic : Same variable name inside and outside the loop
3rd Sep 2022, 2:47 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 1
https://en.m.wikipedia.org/wiki/Variable_shadowing As a standard it's not advisable to use this feature....
3rd Sep 2022, 5:04 AM
Sanjay Kamath
Sanjay Kamath - avatar
0
yes
3rd Sep 2022, 8:48 AM
Alem Gilo
Alem Gilo - avatar
0
int i; int main() { for (int i=1;i<=4;i++) cout<<setw(3)<<i<<endl; return 0; }
3rd Sep 2022, 4:25 PM
Mahima Bhardwaj
Mahima Bhardwaj - avatar
0
This was from the test battery 🔋.
4th Sep 2022, 12:35 AM
Sanjay Kamath
Sanjay Kamath - avatar