Constexpr function returns a string literal

Function returning a copy of an integer literal

int number() { return 1; } 

can be easily converted to a simple compilation expression using the constexpr .

 constexpr int number() { return 1; } 

However, I am embarrassed when it comes to string literals. The regular method returns a pointer to const char , which points to a string literal,

 const char* hello() { return "hello world"; } 

but I think that just changing โ€œconstโ€ to constexpr not what I want (as a bonus, it also gives a compiler warning with an outdated conversion from string constant to โ€œchar *โ€ using gcc 4.7.1)

 constexpr char* hello() { return "hello world"; } 

Is there a way to implement hello() so that the call is replaced with a constant expression in the example below?

 int main() { std::cout << hello() << "\n"; return 0; } 
+6
source share
2 answers

const and constexpr not interchangeable , in your case you do not want to discard const , but you want to add constexpr like this:

 constexpr const char* hello() { return "hello world"; } 

The warning you get when casting const is that the string literal is an array of n const char , so the pointer to the string literal should be * const char **, but in C the string literal is an char array, although undefined behavior tries them modify, it was maintained for backward compatibility, but it depreciates, so it should be avoided.

+6
source

Constexpr forced evaluation:

 constexpr const char * hi = hello(); std::cout << hi << std::endl; 
+1
source

All Articles