Section 6.5.2.5 of the ISO/IEC 9899:1999 (C99) standard defines a compound literal as \[ [ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Wiki Markup
A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers ... The value of a compound literal is that of an unnamed object initiated by the initializer list
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), and the storage duration is associated with its immediate enclosing block (\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\], Section 6.5.2.5.6). Wiki Markup
For example, in the function
Code Block |
---|
void func(void) { int *ip = (int[4]){1,2,3,4}; /* ... */ } |
following initialization, the {{ Wiki Markup int
}} pointer {{ip
}} contains the address of an unnamed object of type {{int
\ [4
\]
}}, allocated on the stack. Once {{func
}} returns, any attempts to access this object will produce undefined behavior.unmigrated-wiki-markup
Note that only one object is created per compound literal \ -\- even if the compound literal appears in a loop and has dynamic initializers (\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\], Section 6.5.2.5.16).
This recommendation is a specific instance of rule DCL30-C. Declare objects with appropriate storage durations.
Noncompliant Code Example
In this noncompliant code example, the programmer mistakenly assumes that the elements of the {{ Wiki Markup ints
}} array of the pointer to {{int_struct
}} are assigned the addresses of distinct {{int_struct
}} objects, one for each integer in the range \ [0, MAX_INTS-1\]:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> typedef struct int_struct { int x; } int_struct; #define MAX_INTS 10 int main(void){ size_t i; int_struct *ints[MAX_INTS]; for (i = 0; i < MAX_INTS; i++) { ints[i] = &(int_struct){i}; } for (i = 0; i < MAX_INTS; i++) { printf("%d\n", ints[i]->x); } } |
...