Let's simply things a little bit:
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <iostream>
int global_var;
int main() {
static int static_var;
int normal_var;
std::cout << global_var << "\n"; // always 0
std::cout << static_var << "\n"; // always 0
std::cout << normal_var << "\n"; // undefined behaviour!
}
|
Why? What's happening?
Well, basically, in C++ if you don't initialize a variable to something it undergoes what's called "default initialization" (see
https://en.cppreference.com/w/cpp/language/default_initialization for lots of details). Default initialization for non-class types results in, well, "something". In essence, that's what's happened to
normal_var — default initializing for a normal type like
int could result in anything.
But what about
global_var and
static_var? Well, C++ also says that variables with "static storage duration"; in other words, globals, static variables, thread local variables, and so forth, get zero initialized before any other initialization happens (again, see
https://en.cppreference.com/w/cpp/language/zero_initialization for lots of details). Then when they get default initialized, nothing happens and they stay 0.
In your example, when you defined
yam globally it got zero-initialized first, so it got filled with 0s. However, when you defined
yam inside a function, it did not get zero-initialized, and was instead filled with junk.