I don't understand what the following code example does and how it does it:
#include <stdio.h>
int f();
int a = f(); // a exists just to call f
int x = 22;
int f() {
++x;
return 123; // unimportant arbitrary number
}
int main() {
printf("%d\n", x);
}
When this is ran it prints 23
, which is the intuitive answer.
However in C++, global variables are supposed to be initialized in order of definition. That would mean that a
should be initialized before x
, because it is defined before x
. If that was the case, then the function f
would have to be called before x
was initialized, because the call to f
is a part of a
's definition.
If f
is indeed called before x
is initialized, that would mean that f
would try to increment x
-- the result of which I'm not really certain of (most likely UB, or some gibberish value). Then, after a
is initialized, x
would be initialized to 22
and the program would print out 22
.
Evidently that's not what happens. But what does? What does that code actually do?
It definitely seems like x
is set to 22
before a = f()
is evaluated, but that would mean that the order of initialization is reversed (I could also be wrong about what initialization is, or when it happens).