Hacker News new | ask | show | jobs
by detrino 3696 days ago
Your loop:

    void TestSigned(int min, int max, int step) {
      for (int i = max; i >= min; i -= step) F(i);
    }
Becomes this with unsigned:

    void TestUnsigned(unsigned min, unsigned max, unsigned step) {
      while (true) {
        F(max);
        if (max < min + step) break;
        max -= step;
      }
    }
Now if I want to transform my loop to operate on pointers or iterators, the transformation is trivial:

    void TestUnsigned(unsigned *min, unsigned *max, unsigned step) {
      while (true) {
        F(*max);
        if (max < min + step) break;
        max -= step;
      }
    }
Quick: Do the same for yours.
1 comments

It looks easy but it isn't.

The second example causes unexpected behavior (and probably ub later) if: min + step > MIN_TYPE_MAX

The last example causes undefined behavior if: max - min < step - 1.