Found in some legacy cruft in our system when investigating why a particular value was coming out as negative (this code wasn't the problem, the problem was this function getting called on the value when it should have been a different function). I have it on reasonable authority that this code is running on a system (not a flight-critical one) on planes. Retyped from memory, probably some mistakes inserted:
double func(double scale, long value, int bits) {
long shift = 1 + std::numeric_limits<long>::digits - bits;
value = (value << shift) >> shift;
return value * scale;
}
Explanation for those of you who are Blakey or Haskell programmers: This function takes a signed integer, extracts a signed twos-complement integer 'bits' long, including sign bit, from the right-hand-side of the integer, multiplies it by a scaling factor, and then returns it. So far so good, this is a reasonable thing to need to do in this context.
Problem: Left-shifting a signed integer in C++ is undefined behaviour if you shift a '1' off the left edge, and this code specifically does that in order to make the return value negative (because all signed integers are twos-complement, right?). Right-shifting signed integers is merely implementation-defined, and fortunately our implementation sign-extends, as is sensible.
I think, but am not certain, that our compiler would have been within its rights to compile value = (value << shift) >> shift
to a no-op. It absolutely would have been within its rights to make everything explode the instant something was shifted into the top bit. We are fortunate that it has decided to be nice to us for the last decadeish and appeared to work. Sure looking forward to the rest of the surprises in all this legacy crap...