Compound literals
suggest changeC99 introduced compound literals: unnamed objects created with a type name followed by an initializer.
struct point {
int x;
int y;
};
draw_point((struct point){ .x = 10, .y = 20 });
A compound literal is an lvalue. At file scope it has static storage duration. Inside a block it normally has automatic storage duration associated with that block, so a pointer to it must not be used after the block's execution has ended.
const struct point *origin(void)
{
static const struct point value = {0, 0};
return &value;
}
Use an explicit static object, as above, when a returned pointer must remain valid. Returning the address of a block-scope compound literal would return a dangling pointer.
Const-qualified compound literals and string literals are not guaranteed to occupy distinct storage, so code must not rely on their addresses being different.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents