0

in C++ int is of 4 bytes that means that int memory it can store 32 bits, then how come

int i = 1;
i = i<<32;
cout<<i<<endl;

gives me the following error:-

main.cpp:7:5: warning: shift count >= width of type
      [-Wshift-count-overflow]
  i <<= 32;

whereas

  int i = 1;
    i = i<<31;
    cout<<i<<endl;

gives me

./main
-2147483648

and

  int i = 1;
    i = i<<30;
    cout<<i<<endl;

gives me

./main
1073741824

what is happening?

Piyush Kumar
  • 191
  • 1
  • 10
  • 2
    What's unclear about "shift count >= width of type"? Shift count = 32; width of type = 32; hence shift count >= width of type is true. – Algirdas Preidžius Apr 24 '20 at 13:28
  • 1
    And your second snippet moves `1` into what is the "sign bit" on **almost all** systems: if this is set, the number is negative. – Adrian Mole Apr 24 '20 at 13:53
  • If you're ever confused, always remember, the most significant bit in a signed `int` has place value `-2^31`. For example, consider if all bit are set. Then total value equals `-2^31 + (2^30 + 2^29 + ... + 2^1 + 2^0) = -2^31 + (2^31-1) = -1`. – srt1104 Apr 24 '20 at 14:12

1 Answers1

1

Let's represent a number in a binary format and see what a left shift does.

for example

    if i = 5        // binary 101
    i<<1 becomes 10 // binary 1010
    i<<2 becomes 20 // binary 10100

and so on

Similarly

    if i = 1          // binary 1
    i<<1 becomes 2    // binary 10
    i<<2 becomes 4    // binary 100
    i<<n becomes 2^n  // binary 1000...n times
    i<<30 becomes 2^30 // binary 1000000000000000000000000000000

If you observe 2^n will require n+1 bits to store, which explains your first error. 2^32 will need 33 bits and std int being 32 bit, you get an overflow error.

Now note that 2^30 occupies 31 bits which are the number of bits allocated to represent the value of int since the 32nd bit is a sign bit (to distinguish between negative and positive numbers).

So, when you do i<<31, the highest order 1 overwrites the sign bit and we get a negative value.

Negative numbers in c++ represented using 2s complement. 2s complement of 2^31 for a 32 bit value is -2147483648 which is what you see.

Now i<<30 when i==1 is just 2^30 or 1073741824

Bugman
  • 191
  • 6