#include <iostream>
int j;
int main(void) {
int i;
std::cout<<i<<std::endl;
std::cout<<j<<std::endl;
return 0;
}
is i can be different value or always be 0? is it right for initial ? is it unexpected result for i?
Your program has undefined behavior, since it requires an lvalue-to-rvalue conversion on an object with indeterminate value (see paragraph 4.1/1 of the C++11 Standard).
In simpler terms, i
does not have any well-defined value, since you are not initializing it, and trying to read its (non-)value is undefined behavior.
Per paragraph 8.5/7 of the C++11 Standard:
To default-initialize an object of type
T
means:— if
T
is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed ifT
has no accessible default constructor);— if
T
is an array type, each element is default-initialized;— otherwise, no initialization is performed.
Also, per paragraph 8.5/12:
If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value. [...]
There is no predefined (default) value for i. By default, some environments may set it to zero (Visual Studio debugger used to do that a few version ago - I don't know if it still does it).
The value for i is undefined. In practice, the value will probably be taken from whatever was in the stack memory at the address that was allocated.