How to set int constant to maximum in C ++?

I have a static constant member and would like to set it to the maximum integer. I am trying to do the following:

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

But get the following error:

error: initializer in class for static data member is not constant Expression

Is there any solution? How can a function not return a constant expression?

EDIT: Adding -std = C ++ 11 fixed the problem. My roommate tells me that the compiler (pre C ++ 11) is not smart enough to decide that std :: numeric_limits :: max () does not mutate anything else and therefore is not considered constant. Perhaps the cause of this error?

+6
source share
3 answers

A constant must be initialized from a constant expression (an expression parsed at compile time).

In C ++ 03, the set of constant operations with which you could build constant expressions was extremely dense. Only bare integrals and mathematical operations on them.

To use a user-defined function in constant expression, you need to:

  • C ++ 11 or more
  • the specified function should be marked constexpr

This is why adding the -std=c++11 flag to Clang helped: it allowed constexpr "switch" to an improved implementation of the standard library that uses constexpr for std::numeric_limits<T>::max() .

Note. If you are using a newer version of Clang, C ++ 11 will be the default, and the constexpr flag constexpr not be needed.

+1
source

Like this:

 #include <climits> const static int MY_VALUE = INT_MAX; 
+1
source

If a static data member has a const constant or a const enumeration of type, its declaration in the class definition may indicate a constant initializer, which should be an integral constant expression (5.19). In this case, the term may appear in the integral constant expression.

An element still needs to be defined in the namespace area if it is used in the program, and the namespace area definition should not contain an initializer.

numeric_limits max() not an integral constant that compiles a time constant.

0
source

All Articles