Default User said:
Bill said:
char array[10] = "abcdefghij";
It's unfortunate that this doesn't generate a
compiler warning in the same way that
int array[2] = { 1, 2, 3}; does.
I think the latter is a constraint violation. That's not true for the
first, it's perfectly legal, although questionable and of course a
warning could be issued if the compiler felt like it.
For those not aware of the rule:
char s[] = "abc";
/* char s2[2] = "abc"; */
char s3[3] = "abc";
char s4[4] = "abc";
char s5[5] = "abc";
s is a 4-byte array containing { 'a', 'b', 'c', '\0' }.
s2, I believe, is a constraint violation.
s3 is a 3-byte array containing { 'a', 'b', 'c' }; it is *not* a string.
s4, like s, is a 4-byte array containing { 'a', 'b', 'c', '\0' }.
s5 is a 5-byte array containing { 'a', 'b', 'c', '\0', '\0' }.
The only way (I think) for a string literal to specify a non-string
(i.e., an array with no '\0' terminator) is to use it as the
initializer for an array of exactly the right size. I suspect we'd be
better off without this rule, which often leads to incorrect code
where the programmer *meant* to create a valid string. Perhaps a
special syntax to indicate that a string literal represents an array
not terminated with a '\0' would have been useful.
If you just want a string with no additional space, use the "[]" form
and let the compiler figure out the required size. As I recently said
here in another thread, counting is what computers are best at; let
the compiler do it for you.