Is it legal to have code (which compiles to assembly instructions in the global scope of a C++ source file? Previously, I was under the impression that except for the Ch programming language (an interpreter for C/C++), you cannot have code in the global scope of a C++ program. Code/instructions can only be inside the body of a function [period]!
However, I found out that you can call functions before the main function in C++ by assigning them to a global variable! This would involve a call
instruction in the assembly code. Also you can assign the sum of two variables into another global variable outside the assembly code. That would almost certainly involve an add
and mov
instructions. And if that code is in the global scope, outside of any function, when would it execute? If the +
were an overloaded operator of a class type, if it had a print statement inside of it, when would that execute?
Also can you have loops and control structures in the global scope of a C++ program, and if so when are they executed? What about for other program constructs, are they allowed in the global scope, and under what circumstances, and when are they executed?
This question is in a response to a previous question that I posted: Why can't I assign values to global variables outside a function in C?
The answerer to the original question asserts that you cannot have code outside of the scope of a function. I think that I do not fully understand the rules for this, and what exactly is considered to be "code" or not.
int foo() {
cout << "Inside foo()" << endl;
return 5;
}
// is this not code?
int global_variable = foo();
// How does this statement work without generating code?
int a = 4;
int b = 5;
int c = a + b;
int main() {
// The program behaves as if the statements above were executed from
// top to bottom before entering the main() function.
cout << "Inside main()" << endl;
cout << "int c = " << c << endl;
return 0;
}