Compound Literals

Suppose you want to pass a value to a function with an int parameter; you can pass an int variable, but you also can pass an int constant, such as 5. Before C99, the situation for a function with an array argument was different; you could pass an array, but there was no equivalent to an array constant. C99 changes that with the addition of compound literals. Literals are constants that aren't symbolic. For example, 5 is a type int literal, 81.3 is a type double literal, 'Y' is a type char literal, and "elephant" is a string literal. The committee that developed the C99 standard concluded that it would be convenient to have compound literals that could represent the contents of arrays and of structures.

For arrays, a compound literal looks like an array initialization list preceded by a type name that is enclosed in parentheses. For example, here's an ordinary array declaration:

int diva[2] ={10, 20};

And here's a compound literal that creates a nameless array containing the same two int values:

(int [2]) {10, 20}  // a compound literal

Note that the type name is what you would get if you removed diva from the earlier declaration, leaving int [2] behind.

Just as you can leave out the array size if you initialize a named array, you can omit it from a compound literal, and the compiler will count how many elements are present:

(int []){50, 20, 90}  // a compound literal with 3 elements

Because these compound literals are nameless, you can't create them in one statement and then use them later. Instead, you have to use them somehow when you make them. One way is to use a pointer to keep track of the location. That is, you can do something like this:

int * pt1;
pt1 = (int [2]) {10, 20};

Note that is literal constant is identified as an array of intS. Like the name of an array, this translate to the address of the first element, so it can be assigned to a pointer-to-int. You then can use the pointer later. For example, *pt1 would be 10 in this case, and pt1[1] would be 20.

Another thing you could do with a compound literal is pass it as an actual argument to a function with a matching formal parameter:

int sum(int ar[], int n);
...
int total3;
total3 = sum((int []){4,4, 4, 5, 5, 5}, 6);

int (*pt2)[4]; // declare a pointer to an array of 4-int arrays
pt2 = (int [2][4]) {{1, 2, 3, -9, {4, 5, 6, -8}};

 

你可能感兴趣的:(Compound Literals)