On which occasions will c++ initialize variables with zero?
c++, initialization
Solution
http://en.cppreference.com/w/cpp/language/zero_initialization
Zero initialization is performed in the following situations:
- For every named variable with static or thread-local storage duration, before any other initialization.
- As part of value-initialization (i.e. with an empty pair of parentheses or braces) sequence for non-class types and for members of value-initialized class types that have no constructors.
- When a character array is initialized with a string literal that is too short, the remainder of the array is zero-initialized.
Problem
Every variable should be properly defined and initialized(assign a value to it) before being used. However under some circumstances, c++ will set variables with a default value of zero. Like the case below. ``` class A{ ... static int val; ...}; //int val = 10; //This is the usual definition. int val;//Definition without assigning a value. ... A a; //a class A object std::cout<<a.val; ``` The result would be zero. Obviously, the compiler did something to initialize variable a.val to zero. I am curious about when will they do this generally?