我目前正在尝试理解g ++在哪些情况下警告未初始化的变量.考虑以下代码:
#include <iostream>
typedef double barType;
struct foo {
barType bar;
};
int main() {
foo f;
std::cout << f.bar << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
如果我像这样编译它我没有得到警告:
$ g++ -O1 -Wall test.cc -o test
Run Code Online (Sandbox Code Playgroud)
但如果我将barType更改为int:
$ g++ -O1 -Wall test.cc -o test
test.cc: In function ‘int main()’:
test.cc:17: warning: ‘f.foo::bar’ is used uninitialized in this function
Run Code Online (Sandbox Code Playgroud)
警告如何取决于类型?在这两种情况下都没有初始化.
我正在使用:
$ g++ --version
g++ (Ubuntu 4.4.1-4ubuntu9) 4.4.1
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. …Run Code Online (Sandbox Code Playgroud) 考虑以下:
#include <iostream>
int main() {
unsigned int x = 3;
unsigned int y = 5;
std::cout << "a: " << x - y << std::endl;
std::cout << "b: " << ((int)x) - y << std::endl;
std::cout << "c: " << x - ((int)y) << std::endl;
std::cout << "d: " << ((int)x) - ((int)y) << std::endl;
}
$ g++ -Wconversion -Wall uint_stackoverflow.cc -o uint_stackoverflow && ./uint_stackoverflow
a: 4294967294
b: 4294967294
c: 4294967294
d: -2
Run Code Online (Sandbox Code Playgroud)
我理解为什么"a"没有给出预期的结果.但为什么"b"和"c"失败让我感到困惑.对于"b",我认为在将"x"转换为"int"后,结果将再次为"int".
你能开导我吗?
编辑:编译器不应警告?g ++(Ubuntu/Linaro 4.4.4-14ubuntu5)4.4.5
谢谢, …