Search code examples
cundefined-behaviorbit-shiftinteger-promotion

Is shifting the signed bit of a signed short undefined behaviour in C?


I have heard that shifting into signed bit of an integer, i.e.

int test = INT_MAX;
test = (test<<1) + 1;

is undefined behaviour due to test being greater than INT_MAX. But will this behaviour be encountered in signed short variables, i.e.

short test1 = SHRT_MAX;
test1 = (test1<<1) + 1;

?

At the moment I have not come across any relevant documentation.

EDIT: I know that undefined behaviour will result in the case of integers, but not of short.


Solution

  • When a small integer type is used in most types of expressions, it is promoted to an int (if int can fit all values of the original type), and the expression is then performed on the int.

    This gives two possibilites:

    1. On a platform where int is the same size as short, the shift will be undefined behavior because it shifts into the int's sign bit. (More accurately, the reason is that the result cannot be represented as an int). See C11 6.5.7p4.
    2. On a platform where int has more bits than short, the shift itself will be successful (though it can be undefined if you're shifting by more than 1). However, when you assign the result back into a short variable, the value will not be able to be represented as a short. The actual value that will be assigned is implementation-defined. See C11 6.3.1.3p3.