Frage

In C, a left shift of a negative value is undefined behavior. I've encountered two libraries compiled with Intel's ICC where the offending code was removed. The same code was fine under Clang, Comeau, GCC and MSVC.

Does the standard make any mention of left shifting a negative value 0 places? Is it also undefined?

(The detail I'm curious about is a 0-sized shift, which is no shift at all in practice. So I'm wondering if the language is vague such that a 0-sized left shift may be allowed).

War es hilfreich?

Lösung

Excerpt from C99 with Technical corrigenda TC1, TC2, and TC3 included:

6.5.7 Bitwise shift operators

[...]

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

So, always undefined.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top