turns out this is just another case of "c++ is not c blues"
What I want
const char hex[16] = "0123456789ABCDEF";
the only thing that works
char hex[16] = "0123456789ABCDE"; hex[15] = "F";
are there any compiler options or something I can do to make strings not null terminated in the gcc compiler. so that I can make a(n) constant array
There actually is a partly solution for this issue in C++17: constexpr
functions may return objects of type std::array
. So, instead of initializing a const C array, we initialize a constexpr C++ std::array
instead. This template function strips the terminator:
template<typename CHAR, unsigned long N>
constexpr inline std::array<CHAR, N-1> strip_terminator(const CHAR (&in)[N])
{
std::array<CHAR, N-1> out {};
for(unsigned long i = 0; i < N-1; i++) {
out[i] = in[i];
}
return out;
}
And it can be used as follows:
constexpr std::array<char, 16> hex = strip_terminator("0123456789ABCDEF");
Everything is done at compile time, even with optimization off: The array hex
becomes a constant of the desired size and the desired content, without the unwanted zero termination byte.
No. NUL-terminated strings are intrinsic to the language. You can have a character array though, and set each character one by one:
char hex [] = {'0', '1', '2', ... 'F'};
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