4
const int INFINITY = INT_MAX;

gives me the

expected an identifier

error. Could you please tell what am I missing? I tried to include <cmath> but it did not help.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Rachael
  • 61
  • 1
  • 1
  • 6

2 Answers2

11

The problem is that INFINITY is either a macro from the <cmath> header. This is expanded to an implementation-defined value by the preprocessor before the actual compilation. In the case of GCC (check with g++ -E), the expression (__builtin_inff ()) takes the place of INFINITY, which clearly not a valid identifier.

A quick fix is to give your constant a different name, such that it is not reserved by the implementation (is not a name of a standard macro):

const int infinity = INT_MAX;

But, when it comes to the title of the question:

What is the right way to declare the INFINITY in c++?

refer to this Q&A that suggests this C++ standard library equivalent:

#include <limits>

const int infinity = std::numeric_limits<int>::max();

Note that integers do not have reserved infinity (Inf), or not a number (NaN) and operations that result in a value out of int's range will (still) overflow, as opposed to operations with IEEE floating-point numbers, which according to this Q&A, don't overflow and result in Inf.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • 1
    _"`0x7f800000` being the hexadecimal representation"_ — this can't directly be an implementation of `INFINITY`: it's an `int` literal, which would require a `reinterpret_cast` to become a `float`. In GCC and Clang actual implementation is `(__builtin_inff ())`, while in MSVC it's `((float)(1e+300 * 1e+300))`. – Ruslan May 19 '21 at 21:23
  • @Ruslan Thank you for the correction and investigation. – LogicStuff May 20 '21 at 10:05
0

INT_MAX is the C way. You should use the following in C++ :-

#include <limits>

int infinity = std::numeric_limits<int>::max();
Amitoj
  • 108
  • 3
  • 3
    This doesn't even try to answer the question. It will fail the same way as the OP's version when renaming `infinity` back to `INFINITY`. –  Jan 31 '16 at 09:45
  • At least, it uses the C++ way, and not the C way. +1 for that. – Erik Alapää Jan 31 '16 at 09:49