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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With