Why is C ++ code contained within functions?

As a newbie in C ++, coming from python, I'm not sure why C ++ does not allow you to use code outside a function (in the global namespace?) It seems like this might be useful to do some initialization before calling main () or declare other functions. (I'm not trying to argue with the compiler, I just would like to know how the thinking process is implemented in this way.)

+5
source share
3 answers

When you run the python program, the interpreter goes through it from top to bottom, executing it. In C ++ this does not happen. The compiler builds all your functions into small droplets of machine code, and then the linker connects them. At run time, the operating system calls your function main, and everything comes from there. In this context, code outside functions does not make sense - when will it start?

+12
source

++ Python. . C ++ , , main() (, , .) , C/++ main(), , , , , . . ; , -.

Python if __name__ == "__main__":, ?

, . main(). :

#include <iostream>
using namespace std;

bool RunBeforeMain ()
{
    cout << "Before main()!" << endl;
    return true;
}

// This variable here causes the above function to be called
bool ignore_this_variable = RunBeforeMain ();

int main ()
{
    cout << "Start of main()" << endl;
    return 0;
}

, static main(). , main(). , main(), , atexit().

+3

() - . , , , .

, main(), , .

But if you want to run the code that initiates the state of the program, you should do this only at the beginning of the program and abuse the static variables and do it using some constructor.

+1
source

All Articles