2) before and after the main function is executed
Before the main function is executed, it mainly initializes system-related resources: 1. set the stack pointer 2. initialize static and global variables, that is, the content of the data segment 3. assign the uninitialized global variables to the initial values: Numeric short, int, long, etc. 0, bool is FALSE, pointer is NULL, and so on. bss segment content 4. global object initialization, calling the constructor before main 5. pass the parameters of the main function, argc, argv, and so on to the main function, and then truly run the main function.
After the main function is executed: 1. The Global Object destructor will be executed after the main function; 2. You can register a function with _ onexit, which will be executed after the main function;
If you need to add a piece of code that is executed after the main exit, you can use the onexit () function to register a function.
# Include <stdlib. h> # Include <stdio. h>
Int atexit (void (* function ") (void )); Void fn1 (void), fn2 (void), fn3 (void );
Int main (void ){ Onexit (fn1 ); Onexit (fn2 ); Printf ("This is executed first ."); }
Void fn1 (){ Printf ("This is "); } Void fn2 (){ Printf ("executed next ."); }
|
Result: This is executed first. This is executed next.