Home > Backend Development > C++ > How are Static and Global Variables Initialized in C ?

How are Static and Global Variables Initialized in C ?

DDD
Release: 2024-11-08 07:05:02
Original
1096 people have browsed it

How are Static and Global Variables Initialized in C  ?

Initialization of Static and Global Variables in C

In C , static and global objects with namespace scope are initialized differently than in C. Here's a comprehensive explanation:

Initialization Phases:

C initializes these variables in three phases:

  1. Zero Initialization: All static objects are set to 0.
  2. Static Initialization: Objects with static initializers are initialized.
  3. Dynamic Initialization: Objects requiring code execution for initialization (non-static objects) are initialized.

Initialization of Given Variables:

In your code snippet:

  • global_int1 is initialized to 5 during static initialization.
  • global_int2 is zero-initialized during zero initialization.
  • static_int1 is initialized to 4 during static initialization.
  • static_int2 is zero-initialized during zero initialization.

Storage and Management of Initialization Values:

During compilation, initialization values are stored in the "data" segment of the executable, unless they are const. In that case, they are placed in the "text" segment.

The system loads the "data" segment into memory, initializing static variables with static initializers. Variables with no initializers or dynamic initializers are placed in the "bss" segment, which is zeroed out by the system before code execution.

Additional Note for C 11

C 11 introduces constexpr, allowing some user-defined functions to be static initializations. Thread local variables are also introduced, which further complicates initialization procedures.

The above is the detailed content of How are Static and Global Variables Initialized in 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