Is there a notation to initialize an array in a single-line, such as with an object literal? Here is what I am currently doing:
int arr[] = {1,2,3};
const int* const x = (const int*) &arr;
And I was wondering if there's a way to do the equivalent of something like:
const int* const x = {1,2,3};
CodePudding user response:
Is there a notation to initialize an array in a single-line, such as with an object literal?
Yes, C has had compound literals since C99, and these can be expressed for array types (and for scalar types too, for that matter). The syntax would be similar to what you suggested:
const int* const x = (int[]) {1,2,3};
or
const int* const x = (const int[]) {1,2,3};
or
const int* const x = (const int[3]) {1,2,3};
It is important to understand that the parenthesized type name in each of those is not a typecast operator, but instead an integral part of the syntax for a compound literal: a parenthesized type name followed by a curly-braced initializer list.
It is also important to understand that the object represented by the compound literal has static storage duration if it appears at file scope but automatic storage duration if it appears at block scope, just like a named object.
A compound literal is an lvalue.
In this particular case, in addition to the compound literal itself, the assignment to a pointer makes use of the usual automatic conversion of a value of array type to a pointer to the first array element.
