Jessica.Jin
Jessica.Jin

Reputation: 87

what value will be printed out if it is out of range in C++

I am a rookie in C++ and I have got a question here.

I use an int to print the first 100 power of 2. I know that the outcome will be out of range of an int variable. I am just curious since the result given by the program is 0. How did 0 come out?

Thanks in advance!

My code is as followed:

#include<iostream>

using namespace std;

void main()
{
    int a=1;
    unsigned int b=1;

    for (int i=1;i<=100;i++)     
    { 
        a=2*a;
        b=2*b;
    }

    cout<<"the first 1oo powers of 2 is (using an signed int): "<<a<<endl;
    cout<<"the first 1oo powers of 2 is (using an unsigned int): "<<b<<endl;

    //The fix
    cout<<"Enter a Char to Exit."<<endl;
    char theFix;
    cin>>theFix;
}

Upvotes: 1

Views: 241

Answers (2)

MARS
MARS

Reputation: 101

Since, you're new to C++, you might not know how the computer stores information. Eventually, all integers are broken down into 32-bit binary numbers (a bunch of 1's and 0's).

a = a * 2; // multiplication

a << 1;    // left shift

These two instructions are actually synonymous due to the nature of binary numbers.

For instance, 0....000010 in binary notation == 2 in decimal notation.

So,

2 * 2 = 4  = 0....000100
4 * 2 = 8  = 0....001000
8 * 2 = 16 = 0....010000

and so on...

Since the bit count is capped at 32 for integers, you'll get a huge number 2^32 == 1000....000. When you multiply by 2 again, the number is shifted left again and you end up with 000...000000 = 0.

All further multiplications of 0 = zero, so that's where your final result came from.

EDIT: Would just like to point out that this is one of the only situations where this exact result would occur. If you were to try using the number 3, for example, you would see the expected integer overflow behavior.

Upvotes: 1

Rudy Velthuis
Rudy Velthuis

Reputation: 28836

Multiplying an unsigned integer or a positive signed integer by 2 is like shifting left by 1, while a 0 bit will be shifted in from the right. After 32 iterations (assuming 32 bit integers), the entire value will be all 0 bits. After that, shifting 0 left will not change the outcome anymore.

Upvotes: 4

Related Questions