Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
584 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...