Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will value ever be 0 after shifting by "x <<= 1" repeatedly?

Tags:

c

bit-shift

I am wondering if x will ever reach zero in the following program.

Please consider:

int main ()
{
    int x = 1;
    while (x)
      {
        x <<= 1;
      }
    return 0;
}

Should the expected behavior of this program be exiting normally or looping forever?

like image 522
user1519088 Avatar asked Jul 11 '12 21:07

user1519088


People also ask

What happens when you left shift a number?

The number to the left of the operator is shifted the number of places specified by the number to the right. Each shift to the left doubles the number, therefore each left shift multiplies the original number by 2. Use the left shift for fast multiplication or to pack a group of numbers together into one larger number.

Does the right shift operator automatically fills higher order bits to 0?

Explanation: The right shift operator automatically fills the higher order bit with its previous contents each time a shift occurs. This also preserves the sign of the value.

What happens when you bit shift an integer?

Logical bit shifting may be useful for multiplying or dividing unsigned integers by powers of two. For example, if the value "0001" or "1" is shifted left, it becomes "0010" or "2," shifted to the left again it becomes "0100," or "4." Shifting to the right has an opposite effect of dividing the value by two per shift.

How does Left Shift and Right Shift Work?

The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.


1 Answers

Neither (or both), it runs in undefined behavior when x overflows.

C99 spec section 6.5.7 says:

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.

like image 117
Luchian Grigore Avatar answered Oct 19 '22 05:10

Luchian Grigore