3 ms·
I 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) > si
by Someone 12y ago
I 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.