Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non null-terminated string compiler option for gcc

Update

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

like image 897
GlassGhost Avatar asked Dec 03 '10 17:12

GlassGhost


2 Answers

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.

like image 191
Kai Petzke Avatar answered Oct 27 '22 05:10

Kai Petzke


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'};
like image 34
wallyk Avatar answered Oct 27 '22 05:10

wallyk