[c++] Setting an int to Infinity in C++

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?

This question is related to c++ infinity

The answer is


You can also use INT_MAX:

http://www.cplusplus.com/reference/climits/

it's equivalent to using numeric_limits.


int min and max values

Int -2,147,483,648 / 2,147,483,647 Int 64 -9,223,372,036,854,775,808 / 9,223,372,036,854,775,807

i guess you could set a to equal 9,223,372,036,854,775,807 but it would need to be an int64

if you always want a to be grater that b why do you need to check it? just set it to be true always


This is a message for me in the future:

Just use: (unsigned)!((int)0)

It creates the largest possible number in any machine by assigning all bits to 1s (ones) and then casts it to unsigned

Even better

#define INF (unsigned)!((int)0)

And then just use INF in your code


int is inherently finite; there's no value that satisfies your requirements.

If you're willing to change the type of b, though, you can do this with operator overrides:

class infinitytype {};

template<typename T>
bool operator>(const T &, const infinitytype &) {
  return false;
}

template<typename T>
bool operator<(const T &, const infinitytype &) {
  return true;
}

bool operator<(const infinitytype &, const infinitytype &) {
  return false;
}


bool operator>(const infinitytype &, const infinitytype &) {
  return false;
}

// add operator==, operator!=, operator>=, operator<=...

int main() {
  std::cout << ( INT_MAX < infinitytype() ); // true
}

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();