This question already has an answer here:
In C99 we can use compound literals as unnamed array.
But are this literals constants like for example 100
, 'c'
, 123.4f
, etc.
I noticed that I can do:
((int []) {1,2,3})[0] = 100;
and, I have no compilation error and is guessable that the first element of that unnamed array is modified with 100.
So it seems as array as compound literal are lvalue and not constant value.
As far I remeber you are right, compound literals are lvalues*, you can also take pointer of such literal (which points to its first element):
It is also possible to apply
const
qualifier on such compound literal, so elements are read-only:*Note this not means it's automatically modifiable lvalue (so it can used as left operand for assignment operator) since it has array type and refering to C99 draft
6.3.2.1
Lvalues, arrays, and function designators:It is an lvalue, we can see this if we look at the draft C99 standard section
6.5.2.5
Compound literals it says (emphasis mine):If you want a const version, later on in the same section it gives the following example:
We can find an explanation of the terminology in this Dr Dobb's article The New C: Compound Literals and says:
Compound literals are lvalues and it's elements can be modifiable. You can assign value to it. Even pointer to compound literals are allowed.
Referring to the C11 standard draft N1570:
Section 6.5.2.5p4:
An "lvalue" is, roughly, an expression that designates an object -- but it's important to note that not all lvalues are modifiable. A simple example:
The name
x
is an lvalue, but it's not a modifiable lvalue. (Expressions of array type cannot be modifiable lvalues, because you can't assign to an array object, but the elements of an array may be modifiable.)Paragraph 5 of the same section:
The section describing compound literals doesn't specifically say that whether the unnamed object is modifiable or not. In the absence of such a statement, the object is taken to be modifiable unless the type is
const
-qualified.The example in the question:
is not particularly useful, since there's no way to refer to the unnamed object after the assignment. But a similar construct can be quite useful. A contrived example:
As mentioned above, the array has automatic storage duration, which means that if it's created inside a function, it will cease to exist when the function returns. Compound literals are not a replacement for
malloc
.