14

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);
                                          ^
1

1 Answer 1

15

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Your example uses parameter to produce a constant expression, right? My example do the same. What is the difference?
@embedc - The difference is that your example assumes the argument is unconditionally constexpr, mine does not.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.