Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This compliant solution eliminates the possibility of undefined behavior resulting from a left shift operation on integers, it . It also uses unsigned integers in accordance with INT13-C. Use bitwise operators only on unsigned operands. Smaller sized integers are promoted according to the integer promotion rules (see INT02-C. Understand integer conversion rules).

Code Block
bgColor#ccccff
unsigned int ui1;
unsigned int ui2;
unsigned int sresult;

if ((ui2 >= sizeof(int)*CHAR_BIT) 
  || (ui1 > (INT_MAX >> ui2)) ) 
{
  /* handle error condition */
}
else {
  sresult = ui1 << ui2;
}

...

Code Block
bgColor#ccccff
unsigned int ui1
unsigned int ui2
unsigned int uresult;

/* modulo behavior is allowed on mod1 and mod2 by exception */
unsigned int mod1
unsigned int mod2;  

/* ... */

if ( (ui2 >= sizeof(unsigned int)*CHAR_BIT) 
  || (ui1 > (UINT_MAX  >> ui2))) ) 
{
  /* handle error condition */
}
else {
  uresult = ui1 << ui2;
}

if (mod2 >= sizeof(unsigned int)*CHAR_BIT) {
  /* handle error condition */
}
else {
  /* modulo behavior is allowed by exception */
  uresult = mod1 << mod2; 
}

Noncompliant Code Example (Right Shift)

...