...
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.
Code Block | ||||
---|---|---|---|---|
| ||||
int si1; int si2; int sresult; /* Initialize si1 and si2 */ sresult = si1 << si2; |
...
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 */ uresult = ui1 << ui2; |
...
This compliant solution eliminates the possibility of undefined behavior resulting from a left-shift operation on unsigned integers.
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; } |
...
This noncompliant code example fails to test whether the right operand is greater than or equal to the width of the promoted left operand, allowing undefined behavior.
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui1; unsigned int ui2; unsigned int uresult; /* Initialize ui1 and ui2 */ uresult = ui1 >> ui2; |
...
This compliant solution tests the suspect shift operations to guarantee there is no possibility of undefined behavior.
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; } |
...