How to declare a string constexpr C?

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

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

 #define my_str "hello" 

This means that the compiler inserts the string literal C in every place where I enter this character, and I can get its length at compile time with sizeof.

This is constexpr char * const my_str = "hello";

or const char * constexpr my_str = "hello";

or constexpr char my_str [] = "hello";

or something else?

+11
source share
2 answers

This is constexpr char * const my_str = "hello";

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

or const char * constexpr my_str = "hello";

No. constexpr cannot get there.

It will be well formed:

 constexpr const char * my_str = "hello"; 

but this does not satisfy:

So that I can get its length at compile time with sizeof, etc.


or constexpr char my_str [] = "hello";

This is well formed and you can 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 a null terminator.

+15
source

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 the compile time constant.

+14
source

Source: https://habr.com/ru/post/1271612/


All Articles