Component literals for scalar types

Since c99

compound literals can be used, for example, to initialize pointers:

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

      

while this is commonly used for struct

, it can also be used to initialize anonymous arrays (see example). But if I understood it correctly, initializing the scalar pointer like this:

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

      

... What I'm confusing is a statement on the site gcc

that also allows "compound literals for scalar types and union types, but then a compound literal is equivalent to a cast". Do they just mean that using the operator address &

in front of the anonymous scalar is a form of casting?

+3


source to share


1 answer


By definition, a compound literal does not consist of the &

address-of operator . From N1570 6.5.2.5/p3

Composite Literals:

A postfix expression consisting of a type name in parentheses followed by a list of initializers enclosed in curly braces is a constituent literal part.

Now their statement:

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



is quite wrong if I read it correctly. The main difference between a compound literal and a cast operator is that the former is an lvalue, just like N1570 6.5.2.5/p4

(emphasis mine):

Otherwise (when the type name indicates the type of the object), the type of the compound literal matches the type of the name. In any case, the result is an lvalue .

while the latter is not, 6.5.4/p5

Cast Operators (emphasis mine):

The preceding expression uses the type name in parentheses to convert the expression value to the specified type. This design is called cast .104)

104) The listing does not give an lvalue . Thus, casting to a qualified type has the same effect as casting to an unaccredited version of the type.

+3


source







All Articles