Dave
Dave

Reputation: 690

% (mod) with mixed signedness

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?

Upvotes: 1

Views: 248

Answers (1)

Dave
Dave

Reputation: 690

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 %!

Upvotes: 1

Related Questions