Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When initializing an array, can variables be inside braces?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 constexpr storage-class specifier shall be constant expressions or string literals

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading