Lalit Kumar
Lalit Kumar

Reputation: 33

Why does double type return Infinity?

I made this code in C++ just to check the biggest integer int and double data types can store.

#include<iostream>
using namespace std;
int main() {
    int a, b;
    cin >> a;
    b = a;
    for(int c; a > 1; a = a * b)
        cout << a << "\n";
};

When I input 2 in the code below, the biggest integer printed is 1073741824.

I changed the code to:

#include<iostream>

using namespace std;

double main() {
    double a, b;
    cin >> a;
    b = a;
    for(double c; a > 1; a = a * b)
        cout << a << "\n";
};

The output of the second code quickly from 2 to printing infinity. Why doesn't the code stop at the largest value of double? Why does it stop in the previous code?

Upvotes: 3

Views: 3360

Answers (3)

Eljay
Eljay

Reputation: 5321

Why doesn't the code stop at the largest value of double?

Because infinity > 1 is always true.

Why does it stop in the previous code?

Due to undefined behavior (or platform specific behavior) when a rolls over from 0x40000000 (decimal 1073741824) to 0x80000000 (decimal -2147483648) on your platform, -2147483648 > 1 is false.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234695

The behaviour on overflowing an int is undefined. Because of this it is not possible to elucidate the maximum possible value that can be stored in an int. So we have to rely on a constant that your platform will provide for you: std::numeric_limits<int>::max() is the value of the largest int.

For the double case, technically the behaviour is also undefined. Although if your platform implements IEEE754, then +Inf will eventually be attained by repeated multiplication of a large enough value; a little over 11. The largest double that isn't +Inf that your platform supports is std::numeric_limits<double>::max().

Finally, main is not allowed to return anything other than an int. Didn't your compiler warn you of that?


1 The actual value of "a little" is std::numeric<double>::epsilon(). Acknowledge @YSC.

Upvotes: 6

Useless
Useless

Reputation: 67733

I made this code in C++ just to check the biggest integer int and double data types can store

This is how you get the largest value you can store in a data type:

#include <iostream>
#include <limits>
using namespace std; // not in real code plz

int main() {
    cout << "largest int is " << numeric_limits<int>::max() << '\n';
    cout << "largest double is " << numeric_limits<double>::max() << '\n';
    return 0;
}

Your trial multiplication wouldn't get this right even if it was well-defined: it would just show you the last value of a such that the real maximum is between a and a*b.

Upvotes: 1

Related Questions