Answers to Why this program compiles fine in C & not in C++? explain that unlike the C language, the C++ language does not tolerate an initializer string for a char
array that is not long enough to hold the terminating null character. Is there a way to specify an unterminated char
array in C++ without bloating the string by a factor of four in the source code?
For example, in C and in C++, the following are equivalent:
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'};
Because the string "Hello from Stack Overflow"
has length 25, these produce a 26-element char
array, as if the following had been 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'};
In C only, a program can exclude the terminating null character, such as if the string's length is known out of band. (Look for "including the terminating null character if there is room" 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 valid. If I know I will be manipulating the data with functions in the std::strn
family, not the std::str
family, is there a counterpart in the C++ language to the shorthand syntax of C?
My motivation differs from that of the other question about unterminated char
arrays in C++. What motivates this is that several names of items in a game are stored in a two-dimensional char
array. 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'}
};
If there is no shorthand to declare an unterminated char
array, then maximum-length names will have to be written character-by-character, which makes them less readable and less maintainable than to shorter names.