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?