Search code examples
c++integermaxconstantsnumeric-limits

How to set a const int to maximum in C++?


I have a static const member and would like to set it to the maximum integer. I'm trying the following:

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

But get the following error:

error: in-class initializer for static data member is not a constant expression

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

EDIT: Adding -std=c++11 fixed the issue. My roommate tells me that the compiler (pre C++11) isn't smart enough to decide that std::numeric_limits::max() doesn't mutate anything else, and so is not considered constant. Is that possibly the reason for this error?


Solution

  • A constant must be initialized from a constant expression (an expression evaluable at compile-time).

    In C++03, the set of constant operations you could build constant expressions from was extremely tight. Only bare integrals and mathematical operations on those.

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

    • C++11, or greater
    • said function to be marked constexpr

    This is why adding the -std=c++11 flag to Clang helped: it allowed constexpr and "switched" to the improved Standard Library implementation which uses constexpr for std::numeric_limits<T>::max().

    Note: if you use a more recent version of Clang, C++11 will be the default and no flag will be necessary to allow constexpr.