char *names[] = {
[3] = "foo",
[1] = "bar",
[0] = "man"};
int i;
for (i=0; i<sizeof(names)/sizeof(char); i++)
{
puts(names[i]);
}
What are the function of the brackets in the above declaration? Also, why does the resulting loop iterate 3 times instead of 4 and produce this output:
man
bar
The numbers in brackets are the indices of the initializers. This is a C99 feature.
Given that your example code does use this blemish, the reason you receive the output you do is that “foo” is stored in
names[3], whileNULLis stored innames[2]. Your program crashes when it attempts toputs(names[2])which is the same asputs(NULL).Your loop would otherwise iterate to 16 or 32 iterations — you are dividing by
sizeof(char)for the array element size, and you mean to usesizeof(char *).Better to use this macro:
I suggest never using any C99-specific features, such as these “designated initializers.”
There is a reason that most of the answers you received on this question were confused as to why your loop only output two strings rather than four. That reason is that C99 is not widely recognized by other programmers.
There are several reasons that most programmers aren’t familiar with C99’s more distinctive features. A frequently cited reason is that C99 is more incompatible with C++ than ANSI C, and makes the possibility of future conversion to C++ more difficult. My personal complaint with C99 also makes extensions to ANSI C which are superfluous. An example of a superfluous addition is the example from C99 that you have provided. Don’t use “designated inits.” Do refer to the American National Standards Institute C Standard. Do not refer to the International Standards Organization C99 document.
Most of the features which are “nice to have” form C99 were already available as extensions in all major compilers. Declaring a variable in the for-init-statement is an example of a non-ANSI-C-standard feature which is widely supported. The
complexbuilt-in type is an example of a non-ANSI-C-standard feature that is not widely supported.