P
Peter Nilsson
Keith Thompson said: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.
Yes. [6.7.8p2 cf p14]
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.
Note there's only a null byte terminator for the last string
literal in a sequence of concatenated strings...
puts("Hello" "World"); /* output HelloWord */
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.
You say often, but is that really the case? I've been more
frustrated by C++'s stricter rule than the C's lax one.
Perhaps a special syntax to indicate that a string
literal represents an array not terminated with a '\0' would
have been useful.
I've been very happy with C's existing syntax and semantics in
the case of fixed width initialisors. But in any case, I can't
see the committee giving any consideration to a change.