Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: we are no longer concerned with wrapping for unsigned left shift

...

This compliant solution eliminates the possibility of undefined behavior resulting from a left-shift operation on unsigned integers. Example solutions are provided for the fully compliant case (unsigned overflow is prohibited) and the exceptional case (modulo behavior is allowed).

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

unsigned int mod1; /* modulo behavior is allowed by INT34-EX1 */
unsigned int mod2; /* modulo behavior is allowed by INT34-EX1 */

/* Initialize ui1, ui2, mod1, and mod2ui2 */

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;
}

Modulo behavior resulting from left shifting an unsigned integer type is permitted by this standard.

Noncompliant Code Example (Right Shift)

...