...
The following code 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 greater than or equal to the width of the promoted left operand.
Code Block | ||
---|---|---|
| ||
signed int si1, si2, sresult; unsigned int ui1, ui2, resulturesult; resultsresult = si1 << si2; uresult = ui1 << ui2; |
Compliant Solution (
...
left shift)
Wiki Markup |
---|
This compliant solution |
eliminates the possibility of undefined behavior resulting from a left shift operation on signed and unsigned integers. Smaller sized integers are promoted according to the integer promotion rules \[[INT02-A|INT02-A. Understand integer conversion rules]\]. |
Code Block | ||
---|---|---|
| ||
int si1, si2, sresult; unsigned int ui1, ui2, resulturesult; if ( (si2si1 < 0) || (si2 < 0) || (si2 >= sizeof(int)*CHAR_BIT) || si1 > (INT_MAX >> si2) ) { /* handle error condition */ } else { sresult = si1 << si2; } if ( (ui2 >= sizeof(unsigned int)*CHAR_BIT) || (ui1 > (INTUINT_MAX / (1 << si2ui2))) ) { /* handle error condition */ } result else { uresult = si1ui1 << si2ui2; } |
In C99, the CHAR_BIT
macro defines the number of bits for smallest object that is not a bit-field (byte). A byte, therefore, contains CHAR_BIT
bits.
Non-Compliant Code Example (right shift)
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 /
2E22 E2
. If E1
has a signed type and a negative value, theresulting value is implementation-defined.
...
Code Block | ||
---|---|---|
| ||
signed int si1, si2, result; result = ui1 >> ui2; |
Compliant Solution (left shift)
This compliant solution tests the suspect shift operation to guarantee there is no possibility of unsigned overflow.
...