unintuitive for-loop behavior
Grant Edwards
grant.b.edwards at gmail.com
Fri Sep 30 10:36:44 EDT 2016
On 2016-09-30, Steve D'Aprano <steve+python at pearwood.info> wrote:
> To me, "make for-loops be their own scope" sounds like a joke feature out of
> joke languages like INTERCAL. I'm not aware of any sensible language that
> does anything like this.
In C99 a for loop has its own namespac:
int main(void)
{
for (int i=0; i<5; ++i)
printf("i=%d\n",i);
}
If you try to access 'i' outside the for loop, it's an error, because
it doesn't exist in the file, global or 'main' namespace. It only
exists in the for-loop's namespace.
I think that's an absolutely brilliant feature, and I use it a _lot_
when writing C code. I'm a big fan of minimizing the lifetime/scope
of variables. I wish if/then/else did the same thing:
if ((r=some_function()) != R_SUCCESS)
printf("some_function() failed with status %d\n",r);
--
Grant Edwards grant.b.edwards Yow! I don't know WHY I
at said that ... I think it
gmail.com came from the FILLINGS in
my rear molars ...
More information about the Python-list
mailing list