Felix Dombek
Felix Dombek

Reputation: 14356

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.

Upvotes: 2

Views: 152

Answers (2)

songyuanyao
songyuanyao

Reputation: 172864

First of all, int g_int = 5; (and int g_int;) is not declaration, it's definition.

Is this legal C++?

Yes, and g_int will be initialized with value 5. (BTW: For int g_int; g_int will be initialized with value 0.)

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

Yes, it is guaranteed.

BTW: g_int = 5; in main() is not initialization, it's just assignment. It means that if g_int is used before main() entered, the default value 0 (not 5) will be used.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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

Upvotes: 1

Related Questions