Ludo
Ludo

Reputation: 842

Why does the remainder operator fail with different data types?

I encountered an annoying bug in my code:

length = 60;
index = -1;
rem = index % length;

In the debugger, I saw that rem had value 15, instead of -1, which didn't make any sense to me. It turned out that length was of type unsigned int and index was of type int. Changing the type of length to int resolved the issue.

However, I don't understand what went wrong. Given the definition of the remainder operation ((a/b)*b + a%b == a), I had maybe expected a sign error due to the different types, but I had not expected the random value of 15. (Although 60/4 = 15, so maybe some bits got shifted?)

My question is: why did the remainder operation fail when presented with a signed and an unsigned integer as operands? Which implementation details can cause this?

(Using gcc 4.8.2)

Upvotes: 1

Views: 269

Answers (1)

nos
nos

Reputation: 229108

You have 1 unsigned and 1 signed variable as operands to the binary operator %, in this casethe signed variable is converted to an unsigned type. (You can read a summary of these conversion rules here)

So your -1 is converted to an unsigned value, which will be (assuming int is 32 bit) 0xffffffff 0xffffffff % 60 is 15

Upvotes: 1

Related Questions