Search code examples
c++gccc++14constexprconstant-expression

Why is a parameter not a constant expression in a constexpr function?


Could you please explain why this code doesn't compile?

// source.cpp
constexpr const char* func(const char* s) { return s;}

constexpr bool find(const char *param) {
   constexpr const char* result = func(param);
   return (param == 0);
}

int main()
{
   constexpr bool result = find("abcde");
}

The compile command:

$ g++ -std=c++14 source.cpp

I've tried gcc5.4 and gcc6.4. The error:

source.cpp: In function ‘constexpr bool find(const char*)’:
source.cpp:5:46: error: ‘param’ is not a constant expression
 constexpr const char* result = func(param);
                                          ^

Solution

  • A function parameter is never a constant expression. Remember that constexpr functions are just like regular functions. They can be called at run-time too. So we cannot assume the address passed in param is to something that is a constant expression, and so cannot use it to initialize a constexpr variable or return value.

    You can pass string literals to constexpr functions and produce constexpr results, for instance:

    constexpr bool find(const char *param) {
       return (param[0] == 0);
    }
    
    int main()
    {
       constexpr bool result = find("abcde"); // OK!
    }
    

    The function is callable in a constant expression, when given a constant expression. But it cannot assume it is only ever called in a constant expression (I know, one can go cross-eyed thinking about it).