Can C++ have code in the global scope?

The answer on the question you linked to was talking in a simple way, not using strict C++ naming for constructs.

Being more pedantic, C++ does not have “code”. C++ has declarations, definitions, and statements. Statements are what you probably think of as “code”: if, for, expressions, etc.

Only declarations and definitions can appear at global scope. Of course, definitions can include expressions. int a = 5; defines a global variable, initialized by an expression.

But you can’t just have a random statement/expression at global scope, like a = 5;. That is, expressions can be part of definitions, but an expression is not a definition.

You can call functions before main of course. Global variable constructors and initializers which are too complex to be executed at compile time have to run before main. For example:

int b = []()
{
    std::cout << "Enter a number.\n";
    int temp;
    std::cin >> temp;
    return temp;
}();

The compiler can’t do that at compile-time; it’s interactive. And C++ requires that all global variables are initialized before main begins. So the compiler will have to invoke code pre-main. Which is perfectly legal.

Every C++ compilation and execution system has some mechanism for invoking code before and after main. Globals have to be initialized, and object constructors may need to be called to do that initialization. After main completes, global variables have to be destroyed, which means destructors need to be called.

Leave a Comment