Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

By Left shifting, can a number be set to ZERO

I have a doubt in Left Shift Operator

int i = 1;
i <<= (sizeof (int) *8);
cout << i;

It prints 1.

  1. i has been initialized to 1.
  2. And while moving the bits till the size of the integer, it fills the LSB with 0's and as 1 crosses the limit of integer, i was expecting the output to be 0.

How and Why it is 1?

like image 958
SivaSu Avatar asked Dec 01 '22 06:12

SivaSu


2 Answers

As cnicutar said, your example exhibits undefined behaviour. That means that the compiler is free to do whatever the vendor seems fit, including making demons fly out your nose or just doing nothing to the value at hand.

What you can do to convince yourself, that left shifting by the number of bits will produce 0 is this:

int i = 1;
i <<= (sizeof (int) *4);
i <<= (sizeof (int) *4);
cout << i;
like image 44
bitmask Avatar answered Dec 04 '22 21:12

bitmask


Let's say sizeof(int) is 4 on your platform. Then the expression becomes:

i = i << 32;

The standard says:

6.5.7-3

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.

like image 111
cnicutar Avatar answered Dec 04 '22 23:12

cnicutar