Hacker News new | ask | show | jobs
by derf_ 46 days ago
> Previously, in C89, left shift on signed integers was completely undefined...

No, it was implementation defined, which is very different. Every implementation you were ever likely to encounter defined it reasonably. Making some of it undefined now has created a bunch of code that uses macros to cast back and forth between unsigned to get the expected behavior (or, for cases where it is provable that the result is representable, to replace the left shift with a multiplication and hope the optimizing compiler translates it back, because compilers now warn on any left shift of a negative value, despite the fact that the semantics are supposed to be the same as the corresponding multiplication now).

In other words, it created a mess for basically no reason.

1 comments

This is the complete definition of the behavior of left shift operators in C89:

> The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 multiplied by the quantity, 2 raised to the power E2, reduced modulo ULONG_MAX+l if E1 has type unsigned long, UINT_MAX+1 otherwise. (The constants ULONG_MAX and UINT_MAX are defined in the header <limits.h>.)

You notice what's not mentioned there? What happens if E1 is signed. The standard says nothing. And when the standard says nothing, it's undefined behavior.

The behavior at the bit level seems very well defined based on that excerpt. You would need to know how signed integers are defined to know what the numeric value of the result would be. That sounds like it would be implementation dependent, but also completely predictable. Am I missing something?
From the beginning of Section 3.3 (several pages before the text you quoted in Section 3.3.7):

      Some operators (the unary operator ~ , and the binary operators << ,
  >> , & , ^ , and | , collectively described as bitwise operators)
  shall have operands that have integral type.  These operators return
  values that depend on the internal representations of integers, and
  thus have implementation-defined aspects for signed types.
this only warn that there is some implementation-defined stuff coming next, not that all these operator are free of undefined behaviour