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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.