Search⌘ K

Discussion: Going Global

Understand the difference between local and global variables in C++ and why global variables with static storage duration are automatically zero-initialized. Explore static initialization, variable lifetimes, and the implications for program behavior and optimization through clear examples and explanations.

Run the code

Now, it’s time to execute the code and observe the output.

C++
#include <iostream>
int id;
int main()
{
std::cout << id;
}

Understanding the output

This puzzle looks similar to the Hack the Planet! puzzle; they both use the value of an uninitialized variable id. However, this is not an undefined behavior, and the program prints 0. Why is that?

Local vs. non-local variables

The difference is that the id variables in the “Hack the Planet!” puzzle are local variables, which pop in and out of existence each time the functions are called. They’re said to have automatic storage duration. The id in this puzzle, on the other hand, is a global variable. More precisely, id is a ...