Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left shift of negative values by 0 positions?

Tags:

c

bit-shift

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).

like image 976
jww Avatar asked Apr 05 '14 16:04

jww


People also ask

Can you left shift by a negative number?

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.

Can you left shift by 0?

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.

Can shift operator be applied to negative numbers?

No. the right shift operator mostly works with the positive integers. We must not use a negative number.

How do you shift to the left of a function?

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).


1 Answers

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.

like image 112
Deduplicator Avatar answered Sep 19 '22 09:09

Deduplicator