Search code examples
ccompound-literals

Compound literals for scalar types


Since c99 compound literals can be used to e.g. initialize pointers:

int *p = (int []) {1, 2, 3, 4};

while this is usually used for structs it can be used to initialize anonymous arrays as well (see example). But if I understood this correctly initializing a scalar pointer like this:

int *p = &(int) {4};

is also valid. What I find confusing is the statement on the gcc site that “Compound literals for scalar types and union types are also allowed, but then the compound literal is equivalent to a cast.” Do they simply mean that using the address-of operator & in front of an anonymous scalar is a form of casting?


Solution

  • By definition a compound literal does not consist of & address-of operator. From N1570 6.5.2.5/p3 Compound literals:

    A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal.

    Now, their statement:

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

    is rather wrong if I am reading it correctly. The fundamental difference between compound literal and cast operator is that the former is a lvalue, as by N1570 6.5.2.5/p4 (emphasis mine):

    Otherwise (when the type name specifies an object type), the type of the compound literal is that specified by the type name. In either case, the result is an lvalue.

    while the latter is not, 6.5.4/p5 Cast operators (emphasis mine):

    Preceding an expression by a parenthesized type name converts the value of the expression to the named type. This construction is called a cast.104)

    104) A cast does not yield an lvalue. Thus, a cast to a qualified type has the same effect as a cast to theunqualified version of the type.