0
 #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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
jiafu
  • 6,338
  • 12
  • 49
  • 73

2 Answers2

6

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 if T 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. [...]

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
0

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.

utnapistim
  • 26,809
  • 3
  • 46
  • 82