Reputation: 21
I stumbled upon another basic concept I've missed in Python:
Having this basic for
(foreach) loop:
x = 15
for x in range(10):
continue
print(x)
The value for x
I expected was 15, but instead I got 9.
The same code snippet in C returns x
's original value – 15:
#include <stdio.h>
int main(void)
{
int x = 15;
for (int x = 0; x < 10; x++)
{
continue;
}
printf("%d", x);
return 0;
}
I can't figure out how the variable scope works here.
Since x
is declared outside the for
loop scope, shouldn't a new local variable be created during the lifetime of the loop?
Why is x
being overridden in the Python version then?
Upvotes: 1
Views: 366
Reputation: 22033
This is not the same. In C, you explicitly create a new variable, whereas in Python, you reuse the name in the for
scope, ending up overriding the previous value.
So the C equivalent really is:
#include <stdio.h>
int main(void)
{
int x = 15;
for (x = 0; x < 10; ++x)
{
continue;
}
--x; // To accommodate the different behavior of the range loop
printf("%d", x);
return 0;
}
Don't forget that in Python, variables are just entries in a dictionary, dynamically created, whereas in C, they are independent, static items.
Upvotes: 3