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);
^
A constant parameter is declared in the case when it is necessary that the value of the transferred object remains unchanged in the body of the called function. This case is possible when the argument's value is passed by the address when function is called.
A constant expression is an expression that can be evaluated at compile time. Constants of integral or enumerated type are required in several different situations, such as array bounds, enumerator values, and case labels. Null pointer constants are a special case of integral constants.
A constant parameter, declared by the keyword const , is a read-only parameter. This means that we can not modify the value of the constant parameter in the function body. Using the const keyword tells the compiler that the value of that parameter will not be changed inside the function.
A constant value is one that doesn't change. C++ provides two keywords to enable you to express the intent that an object is not intended to be modified, and to enforce that intent. C++ requires constant expressions — expressions that evaluate to a constant — for declarations of: Array bounds.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With