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 char
in 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 char
in 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] = {
"steel hammer",
{'p','a','l','l','a','d','i','u','m',' ','h','a','m','m','e','r'}
};
unterminated char
, -, , .