multiple named initialization of same member

Discussion in 'C Programming' started by William Ahern, May 9, 2005.

  1. Is the following legal, and if so is the behavior specified?

    struct s {
    int a;
    const char *b;
    };

    int main(void) {
    struct s test = {
    .a = 12,
    .b = "",
    .a = 16,
    };

    return 0;
    }
    William Ahern, May 9, 2005
    #1
    1. Advertising

  2. William Ahern

    Eric Sosman Guest

    William Ahern wrote:
    > Is the following legal, and if so is the behavior specified?
    >
    > struct s {
    > int a;
    > const char *b;
    > };
    >
    > int main(void) {
    > struct s test = {
    > .a = 12,
    > .b = "",
    > .a = 16,
    > };
    >
    > return 0;
    > }


    Yes (assuming C99) and yes. 6.7.8/19:

    "The initialization shall occur in initializer list
    order, each initializer provided for a particular
    subobject overriding any previously listed initializer
    for the same subobject [...]"

    So your initialization produces test.a == 16, test.b pointing
    to an empty string.

    --
    Eric Sosman, May 9, 2005
    #2
    1. Advertising

  3. William Ahern

    Michael Mair Guest

    William Ahern wrote:
    > Is the following legal, and if so is the behavior specified?
    >
    > struct s {
    > int a;
    > const char *b;
    > };
    >
    > int main(void) {
    > struct s test = {
    > .a = 12,
    > .b = "",
    > .a = 16,
    > };
    >
    > return 0;
    > }
    >

    6.7.8 #19 IMO covers this:
    ,-
    | The initialization shall occur in initializer list order, each
    | initializer provided for a particular subobject overriding any
    | previously listed initializer for the same subobject; all
    | subobjects that are not initialized explicitly shall be initialized
    | implicitly the same as objects that have static storage duration.
    `-

    Cheers
    Michael
    --
    E-Mail: Mine is an /at/ gmx /dot/ de address.
    Michael Mair, May 9, 2005
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page