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.
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.
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
.
INT_MAX is the C way. You should use the following in C++ :-
#include <limits>
int infinity = std::numeric_limits<int>::max();