Infinity problem

Hello,

I need to use infinity in my program.

 
  int max = -oo;



The compiler warns about that. I have tried to include <limits> header file but with no help.

Hope someone can help with this.
An int can only store finite values. Not sure what you need it for but sometimes you can get away with it by instead using the largest possible value std::numeric_limits<int>::max().

Floating point types like double can usually represent infinity std::numeric_limits<double>::infinity(). You can use std::numeric_limits<double>::has_infinity() to make sure.
Ok. C99 Probably supports infinite values for integers.
I doubt it.
There's no such thing as infinity for integers.

That said, you can still pretend there are by choosing the largest or smallest value an integer can hold, just as Peter87 suggests.


For example, a recent program I wrote needed to deal with minimum edge weights on a graph. This made the choice easy: I could express a lack of an edge by using the maximum value.

1
2
3
#include <limits>

const unsigned Infinity = std::numeric_limits <unsigned> ::max();

The only operation necessary for the edges was addition, so all I needed was a function that added two values without overflow:

1
2
3
4
5
6
unsigned add_without_overflow( unsigned a, unsigned b )
{
  unsigned c = a + b;
  if (c < a) c = Infinity;
  return c;
}

Keep in mind the strict requirements that made this work at all:
- I only cared about minimum edge weights (and their sums), meaning that if anything managed to sum up to infinity I didn't care.
- The graph could not have negative edge weights (they represented distances between physical points, which cannot be negative).

After that I could Floyd G up all Warshall-like to my heart's content.

Remember, though, that whenever you use some kind of sentinel value, you must constantly be careful to keep that sentinel value a special case.


If this all sounds messy, it is. Perhaps there is another way to do what you need. What exactly are you trying to do (that makes you want to use an 'infinity' value)?

Hope this helps.
Topic archived. No new replies allowed.