I am trying to initialize an array of size 2 via compound literals, the code with error is as below
int a[2] = (int[2]){1,2};
And the gcc compiler returns the bug saying
error: array initialized from non-constant array expression
From the gnu page for compound literals here https://gcc.gnu.org/onlinedocs/gcc/Compound-Literals.html, it says "If all the elements of the compound literal are (made up of) simple constant expressions suitable for use in initializers of objects of static storage duration, then the compound literal can be coerced to a pointer to its first element and used in such an initializer".
If I correct the above code into
int* a = (int[2]){1,2};
then it compiles successfully. I've also tried
static int a[] = (int [2]) {1, 2};
which also compiles successfully.
I'd like to understand why the original code cannot work, and why the compiler says the array is initialized from non-constant array expression (from my understanding, 1 and 2 inside of the braces are integer literals that can be determined at compile time, hence constants).
1 Answer 1
The C17 standard draft, 6.7.9 tells you there are two ways to initialize an array:
An array of character type may be initialized by a character string literal or UTF–8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
...
Otherwise, the initializer for an object that has aggregate or union type shall be a brace-enclosed list of initializers for the elements or named members.
Perhaps more readable at cppreference.
3 Comments
Explore related questions
See similar questions with these tags.
int a[] = {1,2};static int a[] = (int [2]) {1, 2};also produces diagnostics from gcc