I am new to C and have found that it is common to initialize arrays with constants. I’m curious, is the following code legal?
int a = 1;
int b = 2;
int c = 3;
int array[3] = {a, b, c};
>Solution :
It depends on the lifetime of the variables.
If they are static variables, the initializer must be constant.
int a = 1;
int b = 2;
int c = 3;
int array[] = { a, b, c }; // XXX Error
int main( void ) {
}
const int a = 1;
const int b = 2;
const int c = 3;
int array[] = { a, b, c }; // ok
int main( void ) {
}
If they are automatic variables, this is allowed.
int main( void ) {
int a = 1;
int b = 2;
int c = 3;
int array[] = { a, b, c }; // ok
}
C23 §6.7.11 ¶5 All the expressions in an initializer for an object that has static or thread storage duration or is declared with the
constexprstorage-class specifier shall be constant expressions or string literals