Home >Backend Development >C++ >How does C initialize static and global variables differently from C?

How does C initialize static and global variables differently from C?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 19:37:02464browse

How does C   initialize static and global variables differently from C?

Initialization of Static and Global Variables in C

In C , static and global variables undergo a specific initialization process prior to the execution of the main function. This stands in contrast to C, where such variables are not initialized before main.

Initialization Timeline

Within C , static and global variables experience a three-phase initialization:

  1. Zero Initialization: All variables are initialized to zero.
  2. Static Initialization: Variables with static initialization, such as those with explicit values (e.g., int global_int1 = 5;), are initialized.
  3. Dynamic Initialization: Variables that require code execution for initialization (e.g., int global_int2 = f();) are initialized.

Storage and Management of Initialization Values

During compilation, values for initialization, like 5 and 4 in your example, are stored within the executable file. During initialization, the system places these values into the appropriate memory locations.

Hierarchical Initialization Order

Static and global variables are initialized in the following order:

  • Function/local scope variables (in order of declaration)
  • Static/global variables with initializer (in order of declaration)
  • Dynamically initialized global variables (in an order determined by the compiler)

C's Approach to Initialization

In C, where there is no pre-main initialization procedure for static and global variables, the compiler manages these variables as follows:

  • Zero-initialized variables are assigned a value of 0 at runtime.
  • Variables with non-zero initializers are assigned values directly from the executable file during program startup.
  • Variables with no initializer are left uninitialized unless assigned values later in the code.

Conclusion

Static and global variables in C and C undergo distinct initialization procedures. By understanding these processes, programmers can gain control over variable initialization and avoid unexpected behaviors in their code.

The above is the detailed content of How does C initialize static and global variables differently from C?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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