更改 "uninitialized local variable" 错误的行为

Changing behavior of "uninitialized local variable" error

考虑以下代码:

#include "stdafx.h"
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
  int count123;
  for (int c = 0; c < 10; c++)
  {
    count123 += c;
  }

    return 0;
}

编译后我收到警告:warning C4700: uninitialized local variable 'count123' used

我知道 reason 正在声明 count123 但没有初始化它。

但是如果我在下面的代码中将 count123 声明为全局变量,警告就会消失。

#include "stdafx.h"
using namespace std;

int count123;
int _tmain(int argc, _TCHAR* argv[])
{

  for (int c = 0; c < 10; c++)
  {
    count123 += c;
  }

    return 0;
}

据我所知,将 count123 声明为全局变量会更改其范围,但如何消除警告?请指导。

全局变量是零初始化的(顺便说一下,这同样适用于静态变量)。这就是您没有收到此消息的原因。

这里是标准报价:

8.5/10: Every object of static storage duration is zero-initialized at program startup before any other initialization takes place. In some cases, additional initialization is done later.

全局变量默认初始化为,因此您没有收到任何警告。

您可以轻松获得 C++ standards 的草稿,然后阅读 8.5 初始化程序部分:

10 [ Note: Every object of static storage duration is zero-initialized at program startup before any other initialization takes place. In some cases, additional initialization is done later. —end note ]

全局变量总是由零初始化,想想一个全局指针,用一些随机值初始化,而你在代码中错误地使用了它。 全局初始化使其为NULL,所以你可以检查它并相应地使用它。

— if it has pointer type, it is initialized to a null pointer;

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

全局变量是静态存储变量,默认情况下是零初始化的。更多信息请看答案here.