I read this great too broad question, and encountered some UB I didn't know before.
The main reason for UB I see from time to time is changing a variable twice between two sequence points. Things like: x = x++
or z = y++ + ++y;
. Reading that changing a variable twice between two sequence points is UB helped me see what was the underlying cause in these cases.
But what about things like bit-shift with negatives? (int x = 8 << -1
) Is there a rule that can explain that or should I memorize this as a unique UB possibility?
I looked here and under section Integer Overflows I found bit-shift with negatives was written, but I don't understand why they are related. When int
is shifted by too much, an overflow is caused, but IMO shifting by a negative is simply UB and the problem isn't the bits that are "over the edge"...
Also looked here ,but that didn't answer my question:
The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
So my questions are:
- Specifically, is bit-shift with negatives considered integer overflow and if so, why?
- If not, is it a part of a bigger phenomena?
- Are there (other) unique cases that can't be grouped under one underlying cause?