user2162550 user2162550 - 1 year ago 61
C Question

Using non standard declaration of array in C

I came across the following code which declares

char *
array in
in a non-standard way:

/* Message Type description array */
char *msgType[M_LAST_MSG] =
[M_INIT_MSG] "Init",
[M_RESET_MSG] "Serdes Reset"

are enumerations with corresponding values of 0, 1 and 2.
According to the formal
documentations, the variables inside this array are string (literals) so what is the purpose of using those enumerations in that manner and is there any documentation to back it up?

Compiled with ARM

Answer Source

This syntax allows you to initialize specific elements of an array by index. You can use either int or enum values to specify which array element to initialize. This way, the values you assign don't need to be consecutive.

If for example you had this:

int x[5] = { [2] 3, [4] 7 };

It would be equivalent to this:

int x[5] = { 0, 0, 3, 0, 7 };

In the above example, the enum values specify that elements 0 and 1 of the array are initialized to "Init" and "Serdes Reset".

From section 6.7.8 of the C99 standard:

18 Each designator list begins its description with the current object associated with the closest surrounding brace pair. Each item in the designator list (in order) specifies a particular member of its current object and changes the current object for the next designator (if any) to be that member. The current object that results at the end of the designator list is the subobject to be initialized by the following initializer.

33 EXAMPLE 9 Arrays can be initialized to correspond to the elements of an enumeration by using designators:

enum { member_one, member_two };
const char *nm[] = {
    [member_two] = "member two",
    [member_one] = "member one",
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download