Juan Molina Juan Molina - 9 months ago 33
C++ Question

Mathematical operations in global variable initialization, what does the machine do?

what does the compiler do when initializing global variables using mathematical operations at the right of the "=" sign?


int global1=75;
int global2=32+84;
int global3=(global1+global2);

int main(){
return global3;

the program should return 191 = (75+(32+84))

what I don't know is whether the result calculated at compile time or at run time

Answer Source

32+84 is a "constant expression", which is a term-of-art in both the C and C++ standards for, essentially, an arithmetic expression whose value can be computed without requiring the compiler to know the value of any variable. When a constant expression is used to initialize a global variable, as in your

int global2=32+84;

technically neither the C nor the C++ standard requires the addition to be evaluated at compile time, but you'd be hard-pressed to find a compiler that didn't do it that way. (There are other contexts where the compiler really must evaluate constant expressions at compile time, so it has to have the code to do it, so it may as well do it all the time.)

global1+global2 is not a "constant expression". In C, that means it cannot be used to initialize a global variable; you will get a compile-time error. In C++, it's allowed, and it is unspecified whether the addition happens at compile time or run time. The only guarantee is that global3 will have the correct value by the time main begins to execute; in particular, it might not have the correct value if observed from a constructor for a global object.

(Empirically, g++ 6 computes the value for global3 at runtime, whereas clang++ 3.9 does it at compile time, which confirms that both possibilities do occur in practice.)

(In C++, but not in C, global1+global2 would be considered a constant expression if both global1 and global2 had been declared const.)