3

Is this defined in C99 and C11?

struct A
{
    struct A* first;
    int value;
};

{    // inside a function
    struct A a = { &a }; 
    a.first->value = 123;
}

And using specifier static:

{    // inside a function
    static struct A a = { &a }; 
    a.first->value = 123;
}
this
  • 5,229
  • 1
  • 22
  • 51
  • 7
    Yes, this is fine – M.M Aug 15 '15 at 09:30
  • 1
    Related: http://stackoverflow.com/q/17742142/694576 http://stackoverflow.com/a/16112288/694576 – alk Aug 15 '15 at 09:41
  • 1
    OP was there recently @alk; he was asking about this in the comments but asked a new question instead. Doesn't seem like there was concise information on whether this was well-defined, so I'm glad the question was asked! – Purag Aug 15 '15 at 10:44
  • Even closer related, if not a dupe: http://stackoverflow.com/q/25683034/694576 – alk Aug 15 '15 at 17:22
  • @alk You might want to edit that title. My extensive search didn't find it, since it incorrectly uses the word: reference. – this Aug 15 '15 at 21:10
  • Please do not take my comments as negative criticism. I just put them here for "reference" ;-). And btw, the downvote wasn't me. – alk Aug 16 '15 at 11:15
  • @alk I didn't take them as such. – this Aug 16 '15 at 11:34

1 Answers1

2

This is well-defined behavior.

According to the C Standard §6.2.4 (emphasis mine):

An object exists, has a constant address, and retains its last-stored value throughout its lifetime.

The lifetime of the non-static struct begins with the entry into the block in which it is declared (known as automatic storage duration):

For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.

And if, in the block with which the declaration is associated, you specify an initialization:

[the initialization] is performed each time the declaration is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached.

So upon entering the block, the struct has guaranteed storage and a constant address that you are free to use in an initialization for that struct, since the initialization is guaranteed to happen after the lifetime of the struct has started.

For the static struct,

Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

So the struct has guaranteed storage and a constant address as soon as program execution starts, and its stored value is initialized during that lifetime but prior to the standard execution protocol (calling main(), etc).

Source: C99 draft. The C11 literature for these references is identical.

Here's a demo. This compiles without warnings under -std=c99 -pedantic and -std=c11 -pedantic.

Purag
  • 16,941
  • 4
  • 54
  • 75