#include <iostream>
int a;
void foo();
int main()
{
std::cout << "a = " << a << std::endl;
foo();
return 0;
}
void foo(){
int b;
std::cout << "b = " << b << std::endl;
}
Output:
a = 0
b = 32650
I have created a function named foo
that declares a int
variable and prints it. It prints some junk value because b
is not initialized at the time of declaration then how is a
getting initialized to 0
everytime?
Why is a
initialized to 0
while b
being initialized to some junk value?
In the original version of C++ language standard, all variables with static storage duration were zero-initialized before any other initialization took place.
In modern C++ this initialization stage (aka static initialization ) is split into constant initialization (for variables with explicit constant initializers) and zero initialization (for everything else). Your a
falls into the second category. So your a
is zero-initialized.
Automatic variables of non-class types, like your b
, begin their life with indeterminate values, unless you initialize them explicitly. Using that indeterminate value in an expression leads to undefined behavior.
From draft of c++17 standard (other standards states almost the same):
3.6.2 Initialization of non-local variables [basic.start.init]
...
Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.
...
3.7.1 Static storage duration [basic.stc.static]
...
All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration . The storage for these entities shall last for the duration of the program (3.6.2, 3.6.3).
If you will go deep into definitions, you will find that a
is actually has static storage duration (it is global variable) and therefore it is zero-initialized.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.