开发者

Weird auto-initialization behavior

I learned that auto-variable开发者_StackOverflow中文版s aren't initialized to zero. So the following code will behave correctly and prints random numbers on the screen:

#include <iostream>
using std::cout;
using std::endl;

void doSomething()
{
  int i;
  cout << i << endl;
}

int main()
{
  doSomething();
}

But why won't this snipped behave in the same way ?

#include <iostream>
using std::cout;
using std::endl;

void doSomething()
{
  int i;
  cout << i << endl;
}

int main()
{
  int j;
  cout << j << endl;
  doSomething();
}

This snippet shows:

0
0

Does anyone know why "j" and "i" were suddenly initialized to zero here?


Using an uninitialized variable is undefined behaviour. It's likely you wouldn't get the same behaviour on another compiler. The only 'why' is to be found inside the source code to your specific C++ compiler.


If an initializer is specified for an object, that initializer determines the initial value of an object. If no initializer is specified, a global (§4.9.4), namespace (§8.2), or local static object (§7.1.2, §10.2.4) (collectively called static objects) is initialized to 0 of the appropriate type.

For example:

// Global scope

int    a; // means ‘‘int    a = 0  ;’’
double d; // means ‘‘double d = 0.0;’’

Local variables (sometimes called automatic objects) and objects created on the free store (sometimes called dynamic objects or heap objects) are not initialized by default.

For example:

void f()
{
   int x; // x does not have a well defined value
   // ...
}

From Stroustrup, The C++ Programming Language, 3rd edition, p.83 - §4.9.5

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜