Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare constexpr C string?

I think i quite understand how to use the keyword constexpr for simple variable types, but i'm confused when it comes to pointers to values.

I would like to declare a constexpr C string literal, which will behave like

#define my_str "hello" 

That means the compiler inserts the C string literal into every place where i enter this symbol, and i will be able to get its length at compile-time with sizeof.

Is it constexpr char * const my_str = "hello";

or const char * constexpr my_str = "hello";

or constexpr char my_str [] = "hello";

or something yet different?

like image 732
Youda008 Avatar asked Sep 07 '17 15:09

Youda008


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!

What is constexpr in C?

The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression. Like const , it can be applied to variables: A compiler error is raised when any code attempts to modify the value. Unlike const , constexpr can also be applied to functions and class constructors.

How do you make a string constant in C++?

To define a string constant in C++, you have to include the string header library, then create the string constant using this class and the const keyword.

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?


2 Answers

Is it constexpr char * const my_str = "hello";

No, because a string literal is not convertible to a pointer to char. (It used to be prior to C++11, but even then the conversion was deprecated).

or const char * constexpr my_str = "hello";

No. constexpr cannot go there.

This would be well formed:

constexpr const char * my_str = "hello"; 

but it does not satify this:

So that i will be able to get its length at compile-time with sizeof, etc.


or constexpr char my_str [] = "hello";

This is well formed, and you can indeed get the length at compile time with sizeof. Note that this size is the size of the array, not the length of the string i.e. the size includes the null terminator.

like image 105
eerorika Avatar answered Oct 29 '22 13:10

eerorika


In C++17, you can use std::string_view and string_view_literals

using namespace std::string_view_literals; constexpr std::string_view my_str = "hello, world"sv; 

Then,

my_str.size() is compile time constant.

like image 23
P0W Avatar answered Oct 29 '22 14:10

P0W