0

I encounter the following piece of code, but I don't know why do it in this way. Could any one explain it to me?

char *MPIDI_CH3_Pkt_type_to_string[MPIDI_CH3_PKT_END_ALL+1] = {
    [MPIDI_CH3_PKT_EAGER_SEND] = "MPIDI_CH3_PKT_EAGER_SEND",
    [MPIDI_CH3_PKT_EAGER_SEND_CONTIG] = "MPIDI_CH3_PKT_EAGER_SEND_CONTIG",
};

Zack

1
  • Why not do it this way? In other words, why are you asking? Do you see anything wrong with it? Commented Feb 20, 2014 at 22:45

2 Answers 2

1

This is just using designated initializers, as in the question Designated initializers and omitted elements. For example,

const char *foo[42] = {[1] = "hello", [2] = "world"};

The code given in the question appears to be a way of stringizing constants.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to declare an array of char * pointers. And you have two manifest constants -MPIDI_CH3_PKT_EAGER_SEND and MPIDI_CH3_PKT_EAGER_SEND_CONTIG - with some values that you are not supposed to "know". Now, you want to make elements with indices MPIDI_CH3_PKT_EAGER_SEND and MPIDI_CH3_PKT_EAGER_SEND_CONTIG to point to corresponding string literal values (and leave all other array elements as null pointers).

How can you do that?

In C89/90 you can do it by initializing everything to nulls first and then use assignment to set the proper elements to proper values

char *MPIDI_CH3_Pkt_type_to_string[MPIDI_CH3_PKT_END_ALL+1] = { 0 };
MPIDI_CH3_Pkt_type_to_string[MPIDI_CH3_PKT_EAGER_SEND] = "MPIDI_CH3_PKT_EAGER_SEND";
MPIDI_CH3_Pkt_type_to_string[MPIDI_CH3_PKT_EAGER_SEND_CONTIG] = "MPIDI_CH3_PKT_EAGER_SEND_CONTIG";

In C99 you can use designed initializer feature to do the same thing in the initializatiuon, as a one-liner, which is exactly what is done in your example.

So, the answer to your "why" question would be: because the language feature used in your declaration does exactly what the user wanted to do. There's no other answer.

P.S. The real "why" question here is why they are using char * pointers to point to string literals (instead of const char * pointers). That's a really big "why".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.