+ 2

For loops and variables

Can a variable that was defined in a for loop be called outside the loop?

9th Jun 2019, 7:17 PM
Helen - avatar
3 Answers
+ 6
Nope, it has a local scope and will only exist for the duration of the for-loop. These scope rules are the reason you can have local variables with the same name as a function or a global variable without any clashing. Example in C: const char *msg = "SoloLearn"; int i; /* Output is Hello, World! */ for (i = 0; i < 10; i++) { const char *msg = "Hello, World!"; puts(msg); } puts(msg); /* Output is SoloLearn */ I can't speak for languages other than C, C++, Go and Java. But I imagine it's largely the same across the board.
9th Jun 2019, 7:34 PM
Cluck'n'Coder - avatar
+ 6
Python behaves differently. The for loop does not create its own scope and you can access the last value of the "iteration" variable outside of the loop (as long as you are in the same scope).
10th Jun 2019, 6:16 AM
Thoq! - avatar
+ 1
Thank you so much. This was helpful Cluck'n'Coder
10th Jun 2019, 5:56 AM
Helen - avatar