4 ms·
Ordinarily, unsigned left shift silently shifts bits off the end. 0xffffffff << 0 is 0xffffffff 0xffffffff << 1 is 0xfffffffe .. 0xffffffff << 30 is
by cliffbean 13y ago
Ordinarily, unsigned left shift silently shifts bits off the end.
0xffffffff << 0 is 0xffffffff
0xffffffff << 1 is 0xfffffffe
..
0xffffffff << 30 is 0xc0000000
0xffffffff << 31 is 0x80000000
It is defined to ignore overflow. Therefore, I claim that there's enough consistency here that we can extend the pattern to this:
0xffffffff << 32 is 0x00000000
I claim this really is the mathematically correct answer. It's consistent with the most obvious pattern, and there are no other relevant patterns.
C has chosen to call this undefined behavior instead of returning the correct answer here, and I call that choosing optimization over correctness.
- tel 13y agoThat may be a useful left shift operator, but it's just not C's left shift operator. You can argue the spec is poor, but you cannot argue that the compiler writers are incorrect.
- joosters 13y agoAre you so sure that all architectures that implement a left shift operator work the same way? For example, if you shift left by 'x' they might shift left by 'x modulo 32' With C, you could still use the shift instruction on that architecture. With your 'correct answer', the compiler would have to output instructions to check the value of x prior to the shift. Besides which, shifting is just one specific case. C has an easily understandable and documented behavior: overflow is undefined, no matter how you achieve it. We don't have to go into horrific detail about what happens when you overflow with adds, multiplys, shifts and so on.
- mikeash 13y agoOn some architectures it's the way he wants it (always zero on overflow), on some it's the way you suggest (shift is mod 32), and on some it just generates junk. Bitshifting is an operation that people generally expect to be extremely fast. Adding a check on every single operation generated by a C compiler just to guarantee identical results upon overflow probably would not go over well.