my_question
my_question

Reputation: 3235

What is advantage/consideration to have nameless array

I ran across such C code:

static char *mem_types[M_CNT] = {
    [M_ABC] = "abc",
    [M_DEF] = "DEF",
    [M_XYZ] = "XYZ",
};   

M_CNT is a macro constant; M_ABC, M_DEF and M_XYZ are all enum.

Such declarations look strange to me, or rather, I am wondering what is the advantage to declare a string array like this. I would simply put it as

static char *mem_types[M_CNT] = {
    "abc",
    "DEF",
    "XYZ",
};   

The only thing I can think of is, the declaration can exactly limit the size of each string.

Is there any other consideration?

Upvotes: 3

Views: 200

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726609

This makes your code immune to re-ordering of the enum values. Here is an illustration of how it works:

#include <stdio.h>

enum {
   aa, bb, cc
};

static char *mem_types[3] = {
    [aa] = "abc",
    [cc] = "DEF",
    [bb] = "XYZ",
};

int main() {
    int i;
    for (i = 0 ; i != 3 ; i++) {
        printf("%s\n", mem_types[i]);
    }
}

This is what the program printed. Note how XYZ and DEF have switched places to match the order of the enum.

abc
XYZ
DEF

Upvotes: 3

sblom
sblom

Reputation: 27343

If new lines may be inserted in the array from time to time, the [M_ABC] version is guaranteed to keep the enum values in line with where the corresponding data lives in the array. Additionally, it provides a signal to any developers reading this code that the enum is definitely still in sync with the actual array definition.

This would be preferable to having code reference, say, mem_types[1] somewhere and having to figure out if it's trying to refer to the old meaning or the new meaning of the magic constant 1.

Upvotes: 1

Related Questions