unintuitive for-loop behavior

Steve D'Aprano steve+python at pearwood.info
Sat Oct 1 04:35:15 EDT 2016


On Sat, 1 Oct 2016 02:39 am, Chris Angelico wrote:

> On Sat, Oct 1, 2016 at 12:36 AM, Grant Edwards
> <grant.b.edwards at gmail.com> wrote:

>> In C99 a for loop has its own namespac:
[...]

> I believe that's the same semantics as C++ uses, and I agree, it's
> very convenient. Among other things, it means that nested loops behave
> more like they do in Python, with independent iterators:

*scratches head*

So let me see if I understand this... 

You're suggesting that C99, where for-loops have their own namespaces, is
MORE like Python (where for-loops DON'T have their own namespace), than
C89, which, like Python, DOESN'T give for-loops their own namespace?

That's ... curious.

I'm not saying you're wrong: after spending three quarters of an hour trying
to fix a six line (including one blank line) C program because I
accidentally closed a comment with /* instead of */, I will believe
anything about C[1]. If you tell me that void causes birth defects and
printf is responsible for the police shootings of unarmed black men, I'll
believe every word of it.



> int main(void)
> {
>     for (int i=0; i<5; ++i)
>     {
>         printf("%d:", i);
>         for (int i=0; i<3; ++i)
>             printf(" %d", i);
>         printf("\n");
>     }
> }
> 
> Now, granted, this is not something I would ever actually recommend
> doing, and code review is absolutely justified in rejecting this...

So let me see if I understand your argument... for-loop namespaces are good,
because they let you write code that you personally wouldn't write and
would, in fact, reject in a code review.

O-kay.


> but it's a lot better than pure function-scope variables, where you'd
> get stuck in an infinite loop.

That's the risk that you take when you have a C-style for loop and you
modify the loop variable. There's nothing special about the inner loop in
that regard:


#include <stdio.h>     /* for printf */
int main(void)
  {
    for (int i=0; i<5; ++i)
      {
        printf("%d:", i);
        i = 0;
      }
  }


Solution: don't do that.







[1] Apparently useful error messages are one of those things C programmers
eschew, like type safety, memory safety, and correctness.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list