Define a C ++ char array without a terminator

Answer to Why is this program compiled in C rather than C ++? explain that, unlike C, C ++ does not wrap the initialization string for char, which is not long enough to hold the trailing null character. Is there a way to specify an unterminated array charin C ++ without inflating the string four times in the source code?

For example, in C and C ++, the following equivalents:

const char s[] = "Hello from Stack Overflow";
const char s[] = {'H','e','l','l','o',' ','f','r','o','m',' ','S','t','a','c','k',' ','O','v','e','r','f','l','o','w','\0'};

Since the string "Hello from Stack Overflow"has a length of 25, they create an array of 26 elements char, as if the following were written:

const char s[26] = "Hello from Stack Overflow";
const char s[26] = {'H','e','l','l','o',' ','f','r','o','m',' ','S','t','a','c','k',' ','O','v','e','r','f','l','o','w','\0'};

Only in C can a program exclude a terminating null character, for example, if the length of a string is known outside the range. (Look for "including a terminating null if there is space" in chapter 6.7.9 of the C99 standard.)

const char s[25] = "Hello from Stack Overflow";
const char s[25] = {'H','e','l','l','o',' ','f','r','o','m',' ','S','t','a','c','k',' ','O','v','e','r','f','l','o','w'};

But in C ++ only the second is permissible. If I know that I will manipulate these functions in the family std::strn, and not with the family std::str, is there an equivalent short C syntax in C ++?

My motivation differs from my problem in the issue of unused arrays charin C ++ . What motivates this is that several items in the game are stored in a two-dimensional array char. For example:

const char item_names[][16] = {
    // most items omitted for brevity
    "steel hammer",
    {'p','a','l','l','a','d','i','u','m',' ','h','a','m','m','e','r'}
};

unterminated char, -, , .

+4
1

, ""

, ++: "abc" 'a', 'b', 'c'? , 16.

#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>

template <unsigned int N>
constexpr char get_ch (char const (&s) [N], unsigned int i)
{
    return i >= N ? '\0' : s[i];
}

#define STRING_TO_CHARS_EXTRACT(z, n, data) \
    BOOST_PP_COMMA_IF(n) get_ch(data, n)

#define STRING_TO_CHARS(STRLEN, STR)  \
    BOOST_PP_REPEAT(STRLEN, STRING_TO_CHARS_EXTRACT, STR)


const char item_names[][16] = { // most items omitted for brevity
    "steel hammer",
    STRING_TO_CHARS(16, "palladium hammer"),
    //{'p','a','l','l','a','d','i','u','m',' ','h','a','m','m','e','r'},
};

...

0

Source: https://habr.com/ru/post/1612793/


All Articles