148

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?

daniel gratzer
  • 52,833
  • 11
  • 94
  • 134
  • 1
    You could just use `float`s, which have a value that represents infinity. – Xeo Dec 31 '11 at 21:15
  • 1
    @jozefg - Okay, so it isn't a check the user is after, just the `Max Value` implementation of the language. – keyboardP Dec 31 '11 at 21:19
  • @keyboardP Yeah it looks like it, I mean i used that when i implement algorithms for minimization. – daniel gratzer Dec 31 '11 at 21:21
  • 4
    @jozefg Ha, I figured you were going to implement A*. I was _so_ close! – Etienne de Martel Dec 31 '11 at 21:21
  • @Xeo: If you need discrete values, `float` isn't the solution. It's easy to imagine a data type whose values are `-Infinity`, `INT_MIN`, ..., 0, ..., `INT_MAX`, `+Infinity`. C++ just doesn't happen to provide such a type. – Keith Thompson Dec 31 '11 at 21:22
  • 2
    @jozefg - That makes sense. I thought OP wanted to actually perform the `a>b` check :) – keyboardP Dec 31 '11 at 21:23
  • C++ makes it fairly easy to define a class with the required characteristics. To avoid limiting the *actual* values that can be held in the "underlying" integer, you'd need to maintain a "value is currently infinity" status flag, and check this in the code to override comparison operators, copy/add values, etc. You'd have to override a lot of operators, but it's all just repetitious trivia. – FumbleFingers Jan 01 '12 at 03:50
  • @FumbleFinger: and would probably affect performance significantly. I remember hadving read an article last year where the author complained about the lack of +/-inf and NaN for integers that would be dealt with by the *hardware* instead of the nasty underflow/overflow undefined behavior we get by default. Now if only I could remember where I read it... – Matthieu M. Jan 01 '12 at 12:50
  • @Matthieu M: Don't get me started! In the real world I think OP's request is potty. Theoretical physicists have been slaving for decades to try and get rid of infinities in their equations, but that turns out to be really hard. And here we have a guy wanting to introduce infinity into programming - probably because he doesn't know how, or can't be bothered to design his algorithm and code sensibly in the first place. – FumbleFingers Jan 01 '12 at 13:22
  • @FumbleFingers: still, does not it bother you that `std::numeric_limits::min() - 1 == std::numeric_limits::max()` in most implementations (it's technically undefined) ? Personally, I would rather have it equals `std::numeric_limits::minusinfinity()` and contaminate the rest of the expression. – Matthieu M. Jan 01 '12 at 14:03
  • @Matthieu: I've never used the *numeric_limits* template, but I note that it supports attributes like *can support infinity*, and *is bounded*. If OP really needs a variable capable of supporting infinity he'll need something like that. But if he seriously thought he could somehow get round the problem using a standard "int", he'd probably be out of his depth with that level of abstraction. – FumbleFingers Jan 01 '12 at 15:34
  • @KeithThompson sorry to necro this but just to clarify since I have a similar issue. You are recommending to solve this by using `a = INT_MAX;` right? Or are you reffering to a different function? – Callat Apr 20 '16 at 16:56
  • 1
    @Hikari: No, I'm saying that there is no way to represent infinity in an integer type. You could create a class with overloaded operators. – Keith Thompson Apr 20 '16 at 17:49

6 Answers6

169

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();
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
  • 45
    And if you *really* need infinity as an **int**, write a wrapper class that overloads the comparison operators and has a boolean variable named "is_infinity". –  Dec 31 '11 at 21:22
  • 1
    @WTP Considering he needs that for an Dijkstra's algorithm implementation, I doubt that would be necessary. But it's the most sensible choice otherwise. – Etienne de Martel Dec 31 '11 at 21:25
  • 5
    I added the comment for future visitors who don't implement Dijkstra's algorithm, but need it for something else. :) –  Dec 31 '11 at 21:28
  • 4
    Note that if you use the `int` solution, you must be very careful with arithmetic: adding a positive number to "infinity" will yield a very unexpected result. – Lambda Fairy Aug 01 '14 at 05:56
  • Wrapper class would come in handy for comparing vectors. – dylan Sep 17 '17 at 04:24
  • Is there any way to initialize with -infinity? – mnis.p Aug 24 '18 at 07:21
  • @mnis.p Assuming your implementation uses IEEE 754 doubles, you can then use `-std::numeric_limits::infinity()`. – Etienne de Martel Aug 24 '18 at 14:35
  • One quibble: True enough that integers are "inherently finite." But so are rational and real numbers (and let's not even start on alephs). The special "Inf" value comes from the widely-implemented IEEE 754 standard. If a similar standard was in use for integers, it might very well include Inf, -Inf, -0, and/or Nan -- but implementations typically use only 2's complement for ints (this is a widely-discussed issue for tools like numpy and panda). – TextGeek Oct 14 '22 at 17:15
87

Integers are finite, so sadly you can't have set it to a true infinity. However you can set it to the max value of an int, this would mean that it would be greater or equal to any other int, ie:

a>=b

is always true.

You would do this by

#include <limits>

//your code here

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

//go off and lead a happy and productive life

This will normally be equal to 2,147,483,647

If you really need a true "infinite" value, you would have to use a double or a float. Then you can simply do this

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

Additional explanations of numeric limits can be found here

Happy Coding!

Note: As WTP mentioned, if it is absolutely necessary to have an int that is "infinite" you would have to write a wrapper class for an int and overload the comparison operators, though this is probably not necessary for most projects.

daniel gratzer
  • 52,833
  • 11
  • 94
  • 134
  • 9
    ...and if you want to use `max()` or `infinity()` in a template where the numeric type is unknown you will need to use `+/-infinity()` iff `std::numeric_limits::has_infinity` and otherwise `min()` and `max()` – Ben Jackson Dec 31 '11 at 22:06
14

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

Parth Sharma
  • 441
  • 4
  • 19
Wilmer E. Henao
  • 4,094
  • 2
  • 31
  • 39
  • 13
    I think you mean `#define INF ((unsigned) ~0)`, see [here](https://wandbox.org/permlink/xnRHvLO04NEtC3gs). – Paul Sanders Jun 21 '18 at 23:10
  • This is very interesting but I needed something I could store in an array with other normal integers, I would up just changing everything to doubles and using the numeric limits infinity – Ryan Mckenna Aug 19 '21 at 12:34
  • Casting 0 to int is unnecessary since 0 is already an int. Also !0 == 1, which is hardly near infinity. Even the definition by Paul Sanders is an unsigned integer, and using it to compare with signed ones will likely cause trouble. – Ale Aug 02 '22 at 23:08
13

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
}
bdonlan
  • 224,562
  • 31
  • 268
  • 324
10

You can also use INT_MAX:

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

it's equivalent to using numeric_limits.

nicodjimenez
  • 1,180
  • 17
  • 15
4

I think that a macro INFINITY is defined in header "<cmath>".

It is defined as follows,

#define INFINITY ((float)(1e+300 * 1e+300))

This is such a large number that no other number (at least in c++) can be greater than it. But obviously since we are converting to a type (int), which at max can hold a value 2147483647. So then it would implicitly convert to that value.