Consider following code:
// hacky, since "123" is 4 chars long (including terminating 0)
char symbols[3] = "123";
// clean, but lot of typing
char symbols[3] = {'1', '2', '3'};
so, the twist is actually described in comment to the code, is there a way to initialize char[] with string literal without terminating zero?
Update: seems like IntelliSense is wrong indeed, this behaviour is explicitly defined in C standard.
This
is a valid statement.
According to the ANSI C Specification of 1988:
Therefore, what you’re doing is technically fine.
Note that character arrays are an exception to the stated constraints on initializers:
However, the technical correctness of a piece of code is only a small part of that code’s “goodness”. The line
char symbols[3] = "123";will immediately strike the veteran programmer as suspect because it appears, at face value, to be a valid string initialization and later may be used as such, leading to unexpected errors and certain death.If you wish to go this route you should be sure it’s what you really want. Saving that extra byte is not worth the trouble this could get you into. The NULL symbol, if anything, allows you to write better, more flexible code because it provides an unambiguous (in most instances) way of terminating the array.
(Draft specification available here.)
To co-opt Rudy’s comment elsewhere on this page, the C99 Draft Specification’s 32nd Example in §6.7.8 (p. 130) states that the lines
are identical to
From which you can deduce the answer you’re looking for.
The C99 specification draft can be found here.