| United States-English |
|
|
|
![]() |
HP C/HP-UX Reference Manual: HP-UX Systems > Chapter 3 Data
Types and Declarations 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. The following examples detail the usage of compound literals: 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. struct node In this example, an array of structures has been initialized with the values in the initializer list. (struct node[2]){1,2,3,4} is the compound literal and is assigned to an array of structures st. int main() In this example, a compound literal is passed as a parameter to function foo() instead of creating a temporary variable in the function main() and then passing the compound literal as a parameter to foo(). Compound literals can be passed as parameters to functions eliminating the need of defining a temporary variable in the caller function. int *p=(int [10000]){[999]=20}; This example shows how a particular element[999] in an array of size 10000 can be initialized explicitly. char *c=(char []){"/tmp/testfile"}; This example shows how a compound literal is used to initialize an array of characters. union u This example shows how a compound literal is used as union type. This example shows how the member-wise initialization is done, instead of old order-wise initialization. (const float []) {1e0,1e1}; This example shows a constant compound literal. struct int_list { This example shows how a single compound literal cannot be used to specify a circularly linked object, since compound literals are unnamed. drawline((struct point){.x=1,.y=1},&(struct point){.x=3,.y=3}); /* call */ This example is for structure objects created using compound literals, which are passed to functions. struct st{int a[5],b;}; This example is for a combination of both array and structure initialization. Here w[1].a[3] has a value of 1. struct st { The above example shows how a member-wise initialization using a structure can be done for a compound literal and how initialization would have been done earlier. |
|||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||