¿Por qué falla el operador resto con diferentes tipos de datos?

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 era de tipo int sin firmar e index era de tipo int. Changing the type of length a int resolvió el problema

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)

preguntado el 12 de junio de 14 a las 10:06

@nos: Reopened. Feel free to post that as an answer. -

1 Respuestas

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 aquí)

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

Respondido el 12 de junio de 14 a las 10:06

That answers the question. I had expected that the unsigned integer would be converted to signed integer, because you don't loose information. BUT, I realize now that you can't do that since the range of the unsigned integer wouldn't fit into the signed integer. - Ludo

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.