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;
}
7
  • 7
    Yes, this is fine Commented Aug 15, 2015 at 9:30
  • 1
    Related: stackoverflow.com/q/17742142/694576 stackoverflow.com/a/16112288/694576 Commented Aug 15, 2015 at 9: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! Commented Aug 15, 2015 at 10:44
  • Even closer related, if not a dupe: stackoverflow.com/q/25683034/694576 Commented Aug 15, 2015 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. Commented Aug 15, 2015 at 21:10

1 Answer 1

3

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.

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.