New to c 11 constexpr
, I'm using latest clang -14 version on windows and try to see how const
and constexpr
could work together.
I've got a global variable of char* and wish to return it, in a constexpr
function, as below:
char* pHello = "hello";
constexpr char* hello() {
return pHello; // compilation error
}
It doesn't compile, clang says:
Constexpr function never produces a constant expressionclang(-Winvalid-constexpr)
xxxcpp(20, 12): Read of non-constexpr variable 'pHello' is not allowed in a constant expression
xxx.cpp(18, 7): Declared here
Then in the first line, I added a const
:
const char* pHello = "hello"; // add const here
constexpr char* hello() {
return pHello; // still compilation error
}
This time, the clang error became:
Cannot initialize return object of type 'char *' with an lvalue of type 'const char *'clang(init_conversion_failed)
Reading this error message, I tried to modify the hello()
signature as:
constexpr const char* hello() {
Now the error became same as original:
Constexpr function never produces a constant expressionclang(-Winvalid-constexpr)
xxx.cpp(20, 12): Read of non-constexpr variable 'pHello' is not allowed in a constant expression
xxx.cpp(18, 13): Declared here
I make this test just to see how constexpr
and const
would work together, but even when I change the global variable as also constexpr
like this:
constexpr char* pHello = "hello";
constexpr char* hello() {
return pHello;
}
Still doesn't compile:
error: cannot initialize return object of type 'char *' with an lvalue of type 'const char *'
return pHello;
How to make it work?
CodePudding user response:
The type of pHello
is const char*
(a pointer to const char
), and add constexpr
to make it a constant expression.
The return type of function hello
should be consistent with pHello
, you can't lose constness here. constexpr
here is only used to mark this function a constexpr function.
constexpr const char* pHello = "hello";
constexpr const char* hello() {
return pHello;
}