Why does the code below compile as C++ without complaint, but a C compiler complains that an initializer is not a compile-time constant?
int x = 2;
int y = 1;
int a[2] = {x, y};
#include <stdio.h>
int main()
{
printf("Hello world\n");
return 0;
}
In C, static storage duration objects (such as the global variable
a) must be initialized with constant expressions, whichxandyare not (in either C or C++).In C++ such objects can be initialized with any expression that they could also be initialized by as automatic storage duration variables. However, for global variables the initialization potentially happens at runtime, usually before
mainis entered, and largely in unspecified order. Therefore non-constexprglobal variables like this should be generally avoided if possible or special care needs to be taken that dependencies are initialized in the correct order. C doesn't do any dynamic initialization at runtime.