Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Here's another one. Handy "syntax" that makes it possible to iterate an unsigned type from N-1 to 0. (Normally this is tricky.)

for (unsigned int i = N; i --> 0;) printf("%d\n", i);

This --> construction also works in JavaScript and so on.



It's worth noting that this does also work on signed types, so it can be a kind of handy idiom to see

   while (N --> 0) { ... }
and know it will execute N times no matter the details of the type of N.


AFAICT this would parse as "(i--) > 0", there's no "-->" operator.



If you're gonna test the i--, shouldn't it fall through on zero anyway?

    for (unsigned int i = N; i--;){}

    unsigned int i = N;
    while(i--){ ... }

Also I think I'm missing the tricky part. Couldn't this be a bog-standard for loop?

   for (unsigned int i = N - 1; i > 0; i--){ ... }
The "downto" pseudooperator definitely scores some points for coolness and aesthetics, but there's no immediately obvious use case for me.


The former executes loop when `i` is 0.

And we cannot change the comparison to `>=` in the later, because unsigned is always bigger or equal 0, thus we would get infinite loop.


I was hesitant to put it on the list, but fine, you convinced me


how would you iterate over every possible value of a unsigned int?


Usually I use a do-while loop,

    unsigned char x = 0;
    do {
        printf("%d\n", x);
    } while (++x);


The unary complement operator should get you there:

  unsigned int x = 0;
  const unsigned int max = ~x;

  while (x <= max) {
     calc(x++);
  }
Or,

  #include <limits.h>

  const unsigned int max = UINT_MAX;


This is equivalent to

  while (1) {
    calc(x++);
  }
which is an infinite loop, since the expression x <= max is always true


Heh! Good catch! That is what I get for not testing. After UINT_MAX, x wraps around to 0.


Or if you only wanted to iterate halfway:

    unsigned int x = 0;

    while (x < ~x) {
        calc(x++);
    }
Or going down:

    unsigned int x = ~0;

    while (x > ~x) {
        calc(x--);
    }


By "halfway", did you mean "off by one"?


no




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: