Setting an int to Infinity in C++

Daniel Gratzer picture Daniel Gratzer · Dec 31, 2011 · Viewed 195.5k times · Source

I have an int a that needs to be equal to "infinity". This means that if

int b = anyValue;

a>b is always true.

Is there any feature of C++ that could make this possible?

Answer

Etienne de Martel picture Etienne de Martel · Dec 31, 2011

Integers are inherently finite. The closest you can get is by setting a to int's maximum value:

#include <limits>

// ...

int a = std::numeric_limits<int>::max();

Which would be 2^31 - 1 (or 2 147 483 647) if int is 32 bits wide on your implementation.

If you really need infinity, use a floating point number type, like float or double. You can then get infinity with:

double a = std::numeric_limits<double>::infinity();