Sometimes I am using sequences of characters (strings) except the null terminator is not needed or wanted, for example if I am using memcpy()
and the length is already known. A such, I prefer to omit the null terminator. A cumbersome way to do this would be declaring an array:
char no_term[5] = {'h', 'e', 'l', 'l', 'o'};
However, I would prefer to use quoted strings, as these are much more efficient to program with. However quoted strings automatically include a null terminator at the end. But would specifying the array size to exclude the null terminator invoke undefined behavior? Is the following valid C, as long as I do not use these where a null terminated string is required (e.g., passing them to strlen()
)?
char no_term[5] = "hello";
char no_term_array[3][3] = {"foo", "bar", "baz"};
According to §6.7.9 ¶14 of the ISO C11 standard, arrays of character type may be initialized from a string literal, even if there is no room for the terminating null character.
So yes, your posted code is valid and will not invoke undefined behavior.
Note however that this is only legal in C, not C++. In C++, there must be room for a terminating null character.