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).
The left shift and right shift operators should not be used for negative numbers. The result of is undefined behaviour if any of the operands is a negative number. For example results of both 1 >> -1 and 1 << -1 is undefined. If the number is shifted more than the size of integer, the behaviour is undefined.
Logical left shifts works by multiplying number with 2 n << number = 2*n*number; not in case of number=0; Even if the 0 or the negative numbers are stored in two's complement, so for zero all the bits must be one, then how its logical left shift works.
No. the right shift operator mostly works with the positive integers. We must not use a negative number.
To shift, move, or translate horizontally, replace y = f(x) with y = f(x + c) (left by c) or y = f(x - c) (right by c).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With