Linux gcc - 删除“在此函数中未初始化使用”警告

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19374122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:05:37  来源:igfitidea点击:

gcc - removing "is used uninitialized in this function" warning

c++linuxgcc

提问by dimba

Cleaning code from warning after adding -O2 -Wall flags to gcc (4.4.6). I have a lot of warning in some legacy code. This is very simplified version to demonstrate the problem:

在将 -O2 -Wall 标志添加到 gcc (4.4.6) 后清除警告中的代码。我在一些遗留代码中有很多警告。这是演示问题的非常简化的版本:

 1 #include <cstdio>
  2
  3 bool init(bool& a)
  4 {
  5     return true;
  6 }
  7
  8 int main()
  9 {
 10     bool a;
 11
 12     if (!init(a))
 13     {
 14         return 1;
 15     }
 16
 17     if (a)
 18     {
 19         printf("ok\n");
 20     }
 21 }

When compiling it as "gcc main.cpp -O2 -Wall" I receive:

将其编译为“gcc main.cpp -O2 -Wall”时,我收到:

 main.cpp:17: warning: `a' is used uninitialized in this function

In real code, init() returns true only if it initializes "a", so there's virually no use by uninitialized "a".

在实际代码中,init() 只有在初始化“a”时才返回 true,因此未初始化的“a”实际上没有用处。

Whan can be done to fix the warning.

可以做些什么来修复警告。

采纳答案by Zac Wrangler

change bool a;to bool a = false;will remove this warning.

更改bool a;bool a = false;将删除此警告。

The compiler wont know init(a)is meant to 'initialize a', it only sees the program tries to call a function with a uninitialized variable.

编译器不知道init(a)是为了“初始化一个”,它只看到程序尝试使用未初始化的变量调用函数。

回答by fen

int main()
{
    bool a = false;
    ...

Initialize all variables, always!

始终初始化所有变量!

回答by Daniel Frey

If you don't want to initialize the variable with some value, you can use GCC's diagnostic pragmas:

如果不想用某个值初始化变量,可以使用 GCC 的诊断编译指示

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
   if( a )
#pragma GCC diagnostic pop

This might be handy if your code has performace issues when everything would be initialized. In your example, of course, using bool a = false;is clearly the better choice.

如果您的代码在初始化所有内容时出现性能问题,这可能会很方便。当然,在您的示例中,使用bool a = false;显然是更好的选择。

回答by tristan

add -Wno-uninitialized to your compile option

将 -Wno-uninitialized 添加到您的编译选项