Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr function returning string literal

A function returning a copy of an integer literal

int number()
{ return 1; }

can be easily converted to a plain compile-time expression using the keyword constexpr.

constexpr int number()
{ return 1; }

However, I'm getting confused when it comes to string literals. The usual method is returning a pointer to const char that points to the string literal,

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

but I think that merely changing "const" to constexpr is not what I want (as a bonus, it also produces the compiler warning deprecated conversion from string constant to 'char*' using gcc 4.7.1)

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

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

int main()
{
    std::cout << hello() << "\n";
    return 0;
}
like image 848
jms Avatar asked Mar 21 '14 02:03

jms


People also ask

Can strings be constexpr?

constexpr std::string While it's best to rely on string_views and not create unnecessary string copies, the example above shows that you can even create pass vectors of strings inside a constexpr function!

Can a function be constexpr?

A constexpr function is a function that can be invoked within a constant expression. A constexpr function must satisfy the following conditions: It is not virtual. Its return type is a literal type.

Does constexpr need to be static?

A static constexpr variable has to be set at compilation, because its lifetime is the the whole program. Without the static keyword, the compiler isn't bound to set the value at compilation, and could decide to set it later. So, what does constexpr mean?

How does constexpr work in C++?

constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.


1 Answers

const and constexpr are not interchangeable, in your case you do not want to drop the const but you want to add constexpr like so:

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

The warning you receive when you drop const, is because a string literal is an array of n const char and so a pointer to a string literal should be a *const char ** but in C a string literal is an array of char even though it is undefined behavior to attempt to modify them it was kept around for backwards compatibility but is depreciated so it should be avoided.

like image 153
Shafik Yaghmour Avatar answered Oct 07 '22 08:10

Shafik Yaghmour