When are Static and Global Variables Initialized in C and C ?
In C and C , static and global variables have distinct initialization procedures. Unlike C , where static and global objects undergo construction prior to the main function, C lacks such initialization.
Initialization Timing in C
In C code, global variables like global_int1 and global_int2, which have no explicit initializer, are initialized to 0 by the system. However, static variables static_int1 and static_int2 are not initialized. Their values remain indeterminate until explicitly set within the program.
Initialization Values in C
Variables with explicit initializers, such as global_int1 with the value 5, are assigned their values by the compiler as part of the code's translation. This value is stored in the executable file's data segment.
Upon program execution, the system loads the executable file into memory, including the data segment. The global variables are then allocated memory and initialized with the values stored in the data segment.
Initialization Phases in C
C follows a three-phase initialization process for static objects with namespace scope:
Memory Management in C
Static initialization values in C are stored in the executable file's data segment. Similar to C, these values are loaded into memory during program execution and assigned to the respective variables.
Variables with no initializers or with dynamic initialization are allocated memory in the bss segment. The system initializes these variables to 0 before program execution.
The above is the detailed content of What is the Initialization Process for Static and Global Variables in C and C ?. For more information, please follow other related articles on the PHP Chinese website!