gcc版本 - gcc(Ubuntu 4.8.4-2ubuntu1~14.04.1)4.8.4
使用-Wall -Wuninitialized编译下面的代码会按预期抛出警告 警告:'test'在此函数中未初始化使用[-Wuninitialized]
#include<stdio.h>
#include<stdlib.h>
void check (int test )
{
printf("%d",test);
}
int
main()
{
int test;
check(test);
return 0;
}
但是使用-Wall -Wuninitialized编译下面的代码不会抛出警告
#include<stdio.h>
#include<stdlib.h>
void check (int test )
{
printf("%d",test);
}
int
main()
{
int test;
int condition = 0;
if(condition == 27)
test = 10;
check(test);
return 0;
}
不应该发出警告吗?无论如何它与编译器优化有关吗?
答案 0 :(得分:2)
用户理解为误报可能与特定内容不同 用户。一些用户对由于隐藏的案例感兴趣 优化器的动作与当前环境相结合。 但是,许多用户都不是,因为这种情况是隐藏的 不能出现在编译的代码中。规范的例子是(MM05):
int x; if (f ()) x = 3; return x;
其中&#39; f&#39;总是为当前环境返回非零值,并且 因此,它可以被优化掉。在这里,一群用户愿意 得到未经初步的警告,因为&#39; f&#39;编译时可能返回零 别处。然而,其他一组用户会认为是虚假警告 关于正在编译的可执行文件中不会出现的情况。
https://gcc.gnu.org/wiki/Better_Uninitialized_Warnings#Proposal
编辑:MMO5已经修复
答案 1 :(得分:0)
是的,gcc没有警告你,因为代码已被优化掉了。有些人认为这是正确的,因为编译时配置值可能就是这样。其他人认为这是错误的,因为它隐藏了可能的错误。
你不是第一个注意到GCC这个问题的人。 There's a whole proposal about it
与-Wall
的铿锵声检测到问题,甚至建议修复。
$ make
cc -Wall -g test.c -o test
test.c:15:7: warning: variable 'test' is used uninitialized whenever 'if' condition is false
[-Wsometimes-uninitialized]
if(condition == 27)
^~~~~~~~~~~~~~~
test.c:18:10: note: uninitialized use occurs here
check(test);
^~~~
test.c:15:4: note: remove the 'if' if its condition is always true
if(condition == 27)
^~~~~~~~~~~~~~~~~~~
test.c:12:12: note: initialize the variable 'test' to silence this warning
int test;
^
= 0
1 warning generated.