3 ms·
Actually what's funny here is that (index - 1) % N doesn't work in C, as it can be negative. You have to use (index+N-1) % N. I still prefer 0 based indexing (
by xiphias2 8y ago
Actually what's funny here is that (index - 1) % N doesn't work in C, as it can be negative. You have to use (index+N-1) % N.
I still prefer 0 based indexing (for example for calculating the size of an array), but the worst thing is inconsistency between languages. 0 won, that's it.
- bsder 8y agoOh, 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'.