+ 2
For loops and variables
Can a variable that was defined in a for loop be called outside the loop?
3 Respostas
+ 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.
+ 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).
+ 1
Thank you so much. This was helpful Cluck'n'Coder