GNU C supports constructor expressions. A constructor 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.
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 constructor:
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 constructor are (made up of) simple constant expressions, suitable for use in initializers, then the constructor is an lvalue and can be coerced to a pointer to its first element, as shown here:
char **foo = (char *[]) { "x", "y", "z" };
Array constructors whose elements are not simple constants are
not very useful, because the constructor is not an lvalue. There
are only two valid ways to use it: 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 constructor:
output = ((int[]) { 2, x, 28 }) [input];
Constructor expressions for scalar types and union types are is also allowed, but then the constructor expression is equivalent to a cast.
Go to the first, previous, next, last section, table of contents.