Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The storage for this object is either static if the compound literal occurs at file scope or automatic if the compound literal occurs at block scope, with storage duration associated with its immediate enclosing block (6.5.2.5.6).

For example, in the following function:

...

Wiki Markup
following initialization, the {{int}} pointer {{ip}} contains the address of an unnamed object of type {{int \[4\]}}, allocated on the stack.

Note It should be noted that only one object is created per compound literal -- even if the compound literal appears in a loop and has dynamic initializers (6.5.2.5.16).

...

However, only one int_struct object is created. At each iteration of the first loop, the x member of this object is set equal to the current value of the loop counter i. Therefore, after just before the first loop terminates, the value of the x member is MAX_INTS - 1.

During the print loop, this value is printed MAX_INTS times because every pointer in the "ints" array is set to point to the (single) int_struct object.

Because the storage duration of the compound literal is associated with the for loop that contains it, dereferencing ints in the second loop results in undefined behavior.

Even if the region of memory that contained the compound literal is not written to between loops, the print loop will display the value MAX_INTS-1 for MAX_INTS lines. This is contrary to the intuitive expected result, which is that the integers 0 through MAX_INTS-1 would be printed in order.

...