[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.21 Compound Literals

ISO C99 supports compound literals. A compound literal looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer. (GCC does not yet implement the full ISO C99 semantics for compound literals.) As an extension, GCC supports compound literals in C89 mode and in C++.

Usually, the specified type is a structure. Assume that struct foo and structure are declared as shown:

 
struct foo {int a; char b[2];} structure;

Here is an example of constructing a struct foo with a compound literal:

 
structure = ((struct foo) {x + y, 'a', 0});

This is equivalent to writing the following:

 
{
  struct foo temp = {x + y, 'a', 0};
  structure = temp;
}

You can also construct an array. If all the elements of the compound literal are (made up of) simple constant expressions, suitable for use in initializers, then the compound literal is an lvalue and can be coerced to a pointer to its first element, as shown here:

 
char **foo = (char *[]) { "x", "y", "z" };

Array compound literals whose elements are not simple constants are not very useful, because the compound literal is not an lvalue; ISO C99 specifies that it is, being a temporary object with automatic storage duration associated with the enclosing block, but GCC does not yet implement this. There are currently only two valid ways to use it with GCC: to subscript it, or initialize an array variable with it. The former is probably slower than a switch statement, while the latter does the same thing an ordinary C initializer would do. Here is an example of subscripting an array compound literal:

 
output = ((int[]) { 2, x, 28 }) [input];

Compound literals for scalar types and union types are is also allowed, but then the compound literal is equivalent to a cast.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated by Vincent Chung on June, 26 2001 using texi2html