3 ms·
More portable: x += n % (1 << (SIZEOF_LONG * CHAR_BIT));
by TazeTSchnitzel 12y ago
More portable:
x += n % (1 << (SIZEOF_LONG * CHAR_BIT));
- jevinskie 12y agoPerhaps the C++ standard could add 'operator{+,-,etc}%'.
- TazeTSchnitzel 12y agoAlong the lines of Swift's & operators?
- jevinskie 12y agoYes, those seem quite nice! Edit: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html https://developer.apple.com/library/ios/documentation/Swift/...
- Animats 12y agoIf the program wants 32-bit unsigned modular arithmetic, that's what you should get, regardless of the underlying machine architecture. If you code that, you're probably doing a checksum, and you want the answer to be consistent across platforms.
- Someone 12y agoI don't think SIZEOF_LONG is portable C. You would want sizeof(long) * CHAR_BIT instead (while at it, use sizeof(x) instead, ?and abort if sizeof(n) > sizeof(x)?)). More importantly, I think that expression produces an int value, so if sizeof(long) > sizeof(int), that shift will produce undefined behaviour (or zero? I don't have a C standard to check that on at hand. Actually, shifting any integral type by its size in bits could well be undefined behavior) Even if that weren't the case, that doesn't do modular arithmetic. You would want x = (x + n) % (1 << (SIZEOF_LONG * CHAR_BIT)); and of course, that computes x+n before doing the modulus, so even that doesn't do modular arithmetic. I think one would need custom syntax for making modular arithmetic easy in C. I would suggest something like x += n (mod 37); That may make parsing difficult, though, if one allows expressions after the 'mod'. Alternatively, put the 'do modular arithmetic' thing in the type: modular(43) int x; modular(23) int y; int n = x + y; // error? Summary: this is way harder than it seems. I bet people will find errors in the above that show that conclusively. Edit: yes, it is harder. According to http://blog.regehr.org/archives/738 http://blog.regehr.org/archives/738, left-shifting a signed integer by one bit already can trigger undefined behaviour.