Felix Dombek Felix Dombek - 1 year ago 44
C++ Question

Value-initializing global variables at declaration

I have read some conflicting info about assigning values to global variables at declaration.

Some seem to allow this:

int g_int = 5;

while others say it must be initalized in main:

int g_int;
int main() {
g_int = 5;

I personally have used the first style in Visual Studio 2008–2013 without any problems.

  • Is this legal C++?

  • If it isn't defined in C++, is it still compiler-defined behaviour in MSVC and g++?

  • If it is legal, is assignment of a function result also legal, with the function call guaranteed to be executed before
    ? E.g.
    time_t g_starttime = time();

Answer Source

others say it must be initialized in main

"Others" are wrong: although variables defined inside a translation unit certainly could be assigned in main, they don't have to be assigned in main.

This is perfectly legal in C++. Assignment of a function result also legal, and the initialization is guaranteed to happen before entering main.

Moreover, if you have multiple declarations with initialization inside the same translation unit (i.e. inside the same CPP file) they are guaranteed to be executed in textual order. If you do this

int twoTimes(int i) {
    cout << "Doubling " << i << endl;
    return 2*i;
int a = twoTimes(7);
int b = twoTimes(8);
int main() {

the output is guaranteed to be

Doubling 7
Doubling 8