...
The result of E1 << E2
is E1
left-shifted E2
bit positions; vacated bits are filled with zeros. If E1
has a signed type and nonnegative value and E1
* 2
E2
is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
The following This noncompliant code example can result in undefined behavior because there is no check to ensure that left and right operands have nonnegative values and that the right operand is less than or equal to the width of the promoted left operand.
...
The result of E1 << E2
is E1
left-shifted E2
bit positions; vacated bits are filled with zeros. According to C99, if E1
has an unsigned type, the value of the result is E1
* 2
E2
, reduced modulo one more than the maximum value representable in the result type. Although C99 specifies modulo behavior for unsigned integers, unsigned integer overflow frequently results in unexpected values and resultant security vulnerabilities (see INT32-C. Ensure that operations on signed integers do not result in overflow). Consequently, unsigned overflow is generally noncompliant, and E1
* 2
E2
must be representable in the result type. Modulo behavior is allowed under exception INT36-EX1.
The following This noncompliant code example can result in undefined behavior because there is no check to ensure that the right operand is less than or equal to the width of the promoted left operand.
...
Code Block | ||
---|---|---|
| ||
unsigned int ui1; unsigned int ui2; unsigned int uresult; /* Initialize ui1 and ui2 */ if (ui2 >= sizeof(unsigned int) * CHAR_BIT) { /* handle error condition */ } else { uresult = ui1 >> ui2; } |
Exceptions
INT36INT34-EX1: Unsigned integers can be allowed to exhibit modulo behavior if and only ifas long as the variable declaration is clearly commented as supporting modulo behavior
...
and each operation on that integer is also clearly commented as supporting modulo behavior.
If the integer exhibiting modulo behavior contributes to the value of an integer not marked as exhibiting modulo behavior, the resulting integer must obey this rule.
...