Can I rely on % (modulo) operator in C for negative numbers? -


using gcc:

printf("%i \n", -1 % (int)4); printf("%u \n", -1 % (unsigned int)4); -1 3 

can rely on behaviour across platforms? should explicitly define mod , rem macros sure isn't altered?

the c99 standard says:

6.5.5 multiplicative operators

:

when integers divided, result of / operator algebraic quotient fractional part discarded87). if quotient a/b representable, expression
(a/b)*b + a%b shall equal a.

:

87) called ‘‘truncation toward zero’’

this implies divide rounds towards 0, can rely on it.

note different c++03 standard.

your second line unsigned divide, converting value -1 unsigned int before divide. 1 less power of 2, defined.


Comments

Popular posts from this blog

java - Could not locate OpenAL library -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

sorting - opencl Bitonic sort with 64 bits keys -