Home > Backend Development > C++ > body text

What is the Initialization Process for Static and Global Variables in C and C ?

DDD
Release: 2024-11-05 20:22:02
Original
1047 people have browsed it

What is the Initialization Process for Static and Global Variables in C and C  ?

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:

  1. Zero Initialization: All static objects are initially set to 0.
  2. Static Initialization: Objects with static initialization (e.g., static_int1) are assigned their values.
  3. Dynamic Initialization: Objects with dynamic initialization (e.g., static_int2 or global_int2 if uninitialized in C ) are initialized at runtime through code execution.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template