2 ms·
Oh, that's hilarious. I tested this in Python where it worked fine and forgot that C has a "broken" modulo operator: Python: >>> -1 % 20 19 C: printf
by bsder 8y ago
Oh, that's hilarious. I tested this in Python where it worked fine and forgot that C has a "broken" modulo operator:
Python:
>>> -1 % 20
19
C:
printf("%d\n", (-1 % 20));
-1
Even worse, it still fails even on unsigned:
printf("%d\n", ((unsigned int)0 - (unsigned int)1) % 20);
15
So you still need to add N:
printf("%d\n", ((unsigned int)0 - (unsigned int)1 + 20) % 20);
19
Thanks for the reminder of humility.
(Side Note: For those reading this, the C operator isn't "broken", per se. There are three properties that modulo can adhere to but two of the three are mutually exclusive.)
- deleted 8y ago[deleted]
- m-ou-se 8y agoC does not have a modulo operator. It has a remainder operator, which works perfectly fine. Calling C's `%` a 'broken modulo operator' is like calling `+` a 'broken minus operator'. Quite a few languages have separate operators, keywords, or functions for 'modulo' and 'remainder'.