Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a character array from a constexpr string [duplicate]

Tags:

c++

constexpr

I had code similar to this:

#define STR "ABC"
// ...
char s[] = STR;
puts(s);
s[2] = '!';
puts(s);

And I tried to modernize it with constexpr:

constexpr char STR[] = "ABC"
// ...
char s[] = STR;
puts(s);
s[2] = '!';
puts(s);

But it no longer compiles.

How can I initialize a string on the stack from a constexpr constant without runtime penalty?

like image 880
Paul Avatar asked Apr 29 '26 12:04

Paul


1 Answers

C-style arrays can only be initialized by literals, not by another array or const char*.

You can switch to std::array

constexpr std::array<char,4> STR{"ABC"};
int main() {
std::array s{STR};
// OR: auto s{STR};
}

Unfortunately, it requires specifying the length of the string literal in STR, if you have C++20, you can use std::to_array:

constexpr std::array STR{std::to_array("ABC")};

optionally replacing std::array with auto.

If you do not have C++20, you can still use the implementation from the link above to write your own to_array.

There is also std::string_view and std::span but both are non-owning pointers.

like image 100
Quimby Avatar answered May 02 '26 01:05

Quimby