HP C A.06.05 Reference Manual
Data Types and Declarations
Compound Literal
Chapter 3 67
Compound Literal
Compound literal provide a mechanism for specifying constants of aggregate or union type.
Compound literal is a part of the C99 standards (ISO/IEC 9899:1999: 6.5.2.5). Compound
literals are an easy means of initializing an object of type aggregate or union without having
to allocate a temporary variable for the object. It is represented as an unnamed object with a
type and has an lvalue.
Syntax
(type-name) {initializer-list}
type-name must specify an object type or an array of unknown size. The value of the
compound literal is that of an unnamed object initialized by the initializer list. The object has
static storage if the compound literal occurs outside the body of the function, otherwise it has
automatic storage duration associated with the enclosing blocks.
Examples
The following examples detail the usage of compound literals:
Example 3-1 An Array of Scalars
int *p=(int[]) {1,2};
In this example, an array of size 2 has been declared, with the first two elements initialized to
1 and 2. (int [ ]){1,2} represents the compound literal and it is assigned to a pointer
variable p of type int.
Example 3-2 An Array of Structures
struct node
{
int a;
int b;
};
struct node *st=(struct node[2]) {1,2,3,4};
In this example, a pointer of structures has been initialized with the unnamed compund
literal object. (struct node[2]){1,2,3,4} is the compound literal and is converted to
struct node * and assigned to st.