For loops and variables | Sololearn: Learn to code for FREE!


For loops and variables

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

6/9/2019 7:17:50 PM


3 Answers

New Answer


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.


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).


Thank you so much. This was helpful Cluck'n'Coder