Home  >  Article  >  Backend Development  >  How do C and C Differ in Initializing Static and Global Variables?

How do C and C Differ in Initializing Static and Global Variables?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-05 19:22:02890browse

How do C and C   Differ in Initializing Static and Global Variables?

Initialization of Static and Global Variables

In C and C , variables are categorized based on scope and duration, with static and global variables being those with the longest duration. Understanding their initialization process is crucial for comprehensive code analysis.

C Variable Initialization

Unlike C , C lacks an explicit initialization procedure before the main function. Global and static variables in C are initialized with default values:

  • Uninitialized int variables default to 0.
  • static and extern variables without initializers are set to 0 by the linker.

C Variable Initialization

Unlike C, C initializes global and static objects in three distinct phases:

  1. Zero Initialization: All static objects are initially set to 0.
  2. Static Initialization: Variables with static initializers are assigned their specified values.
  3. Dynamic Initialization: Variables that require execution of code for initialization are initialized.

Value Storage and Assignment

Values used for initialization are stored in the executable during compilation. Here's how this works:

  • Static initialization values are stored in a dedicated section of the executable known as ".data".
  • Uninitialized variables occupy a section called ".bss", which is set to 0 by the operating system.
  • Dynamically initialized variables have no pre-assigned values in the executable.

Example Initialization

Consider the following C code:

<code class="c">int global_int1 = 5;
int global_int2;
static int static_int1 = 4;
static int static_int2;</code>
  • global_int1 is initialized to 5 during static initialization.
  • global_int2 and static_int2 are initialized to 0 during zero initialization.
  • static_int1 is initialized to 4 during static initialization.

Conclusion

Understanding the initialization behavior of static and global variables is essential for effective memory management and reliable code execution. C 's phased initialization process offers greater flexibility and control over variable initialization compared to C's default values.

The above is the detailed content of How do C and C Differ in Initializing Static and Global Variables?. 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