user198736
user198736

Reputation:

Is it valid C to declare a struct and define values enclosed in {}?

Is it valid C to declare a struct and define values enclosed in {}?

struct name new_name[] {
    {"value1"},
    {"value2"},
    {"value3"},
}

Where:

struct name {
    union {
        char *value1;
    } n_u;

    char *value2;
}

Upvotes: 1

Views: 105

Answers (1)

Alan Curry
Alan Curry

Reputation: 14731

What you've posted is invalid because it's missing an equals sign before the initializer (and also trailing semicolons). Otherwise, it's legal but somewhat hard to read because it doesn't initialize every field, and doesn't use a full set of braces. In a fully-braced initializer, you'll have a pair of braces around the list of values for every array, struct, or union. In this case you have an array of structs with unions in them, so there should be 3 levels of braces for optimum readability. An equivalent with everything spelled out is:

struct name new_name[] = {
    {{"value1"}, NULL},
    {{"value2"}, NULL},
    {{"value3"}, NULL},
};

Upvotes: 3

Related Questions