Exactly in order from top to bottom ;) |
Which works fine when you have a single file, i.e. for the most elementary of tutorial exercises. But in the real world...
I have a project with 3 files, A.cpp, B.cpp, and C.cpp, which are linked together to create an application. In which order would this hypothetical global-scope code in these 3 files execute?
Oh, wait, I've already answered it:
The correct answer, even if it were allowed, would be: you wouldn't know when it was executed. This is one of the many problems with using global variables - you can't ever know in which order those objects will be instantiated, and the problem would be even worse if more code execution was allowed outside functions/methods. |
In other words - the creation of stuff in global scope happens in a jumble. It get done in whatever order the compiler - or, rather, the linker - chooses to have it done. This is already problematic when the only execution that happens in the global scope is the instantiation of global objects; how much worse would it be if we were executing more code?
In Python, it's easy, because you don't link files, you "import" them, so when the script interpreter reaches that import line, it begins execution - from top to bottom - of the imported file. It's analogous to the way the C++ preprocessor resolves a #include statement during compilation. But that's compilation - NOT runtime. There is no runtime analogy to Python's "import" statement.
I'm sure you, krakow10, know this already - but there will be people reading this forum who don't.