Bitwise shifts include left-shift operations of the form shift-expression <<
additive-expression and right-shift operations of the form shift-expression >>
additive-expression. The standard integer promotions are first performed on the operands, each of which has an integer type. 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. (see See undefined behavior 51.).
Do not shift an expression by a negative number of bits or by a number greater than or equal to the precision of the promoted left operand. The precision of an integer type is the number of bits it uses to represent values, excluding any sign and padding bits. For unsigned integer types, the width and the precision are the same, ; whereas for signed integer types, the width is one greater than the precision. This rule uses precision instead of width because, in almost every case, an attempt to shift by a number of bits greater than or equal to the precision of the operand indicates a bug (logic error). A logic error is different from overflow, in which there is simply a representational deficiency. In general, shifts should only be performed only on unsigned operands. (see See INT13-C. Use bitwise operators only on unsigned operands.).
Noncompliant Code Example (Left Shift, Unsigned Type)
...
The
macro and PRECISION()
popcount()
function provide the correct precision for any integer type. (see See INT35-C. Use correct integer precisions.).
Modulo behavior resulting from left-shifting an unsigned integer type is permitted by exception INT30-EX3 to INT30-C. Ensure that unsigned integer operations do not wrap.
...
The result of E1 >> E2
is E1
right-shifted E2
bit positions. If E1
has an unsigned type or if E1
has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1
/ 2
E2
. If E1
has a signed type and a negative value, the resulting value is implementation-defined and can be either an arithmetic (signed) shift:
or a logical (unsigned) shift:
This noncompliant code example fails to test whether the right operand is greater than or equal to the precision of the promoted left operand, allowing undefined behavior:
...
When working with signed operands, making assumptions about whether a right shift is implemented as an arithmetic (signed) shift or a logical (unsigned) shift can also lead to vulnerabilities. (see See INT13-C. Use bitwise operators only on unsigned operands.).
Compliant Solution (Right Shift)
...