1

I was working with a toroidal 2D grid in c++ (ie. it wraps around at the sides), and wrote an obvious neighbor / relative-point function:

point neighbor(point p0, int dx, int dy)
{
    point p=p0;
    p.x += dx;
    p.y += dy;
    p.x %= width; if(p.x<0) p.x += width;
    p.y %= height; if(p.y<0) p.y += height;
    return p;
}

I was totally clueless why my program wasn't working, since the implementation of this function seemed trivial.

I thought I understood the % operator, I even remembered to check for negative results. Still, I started experimenting with it; 'width' was an unsigned with a value of 160, so I tried:

cout << (-1) % 160u;

... and I was shocked to see a result of 95.

What the heck is going on?

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
Dave
  • 690
  • 4
  • 7
  • 16

1 Answers1

1

As it turned out, my program didn't cast the unsigned 160u to int.
Rather, -1 is converted to unsigned becoming 4294967295, which in fact gives 95 when modded by 160.

Why c++ does so is beyond me, but I'm posting this so others may learn from my experience. Bottom line: Do not mix signed and unsigned integers when using %!

Dave
  • 690
  • 4
  • 7
  • 16
  • 1
    That promotion (of -1 to 2^32-1) is one of the normal C++ integer promotion rules. You have a `signed int` on one side of the `%` and an `unsigned int` on the other, so the `signed int` gets promoted to `unsigned int` before the operation takes place. If you just take the `u` off your `160u`, you'll get the `-1` you appear to be looking for. Your comment about "do not mix signed and unsigned integers" is generally pretty good advice - at least make sure you know what you're doing. You'll have problems with a lot more than just the `%` operator otherwise. – Carl Norum Oct 13 '12 at 23:55