交付软件给客户却是很多问题,一些问题解决就可以了。但有些问题却是一时出现,一时不出现,十分令人恼火,程序猿是超人也难以应付。本文以编译警告为引入点述说在开发过程中的匪夷所思的问题。引以为鉴,重视警告的影响。
warning: unused variable 'value'.
警告:未使用变量"value"
致命行为:
double sum(double a, double b)
{
return a;
}
...
Car car = new Car();
...
建议:
warning: implicit conversion turns floating-point number into integer: 'double' to 'int'.
警告:隐式转换将浮点数转换为整数:"double"到"int"。
致命行为:
enum Fruits { Apple, Orange, Banana};
Fruits fruits = (Fruits)5; // fruits成不确定值,值取决于编译器。
建议:
warning: field 'j' will be initialized after field 'i'.
警告:字段"j"将在字段"i"之后初始化。
致命行为:
class Car
{
public:
Car () : j(i + 2), i(1) // 由于j先于i初始化,导致j变量的预期结果却不是3。
{
}
private:
int i;
int j;
};
建议:
warning: if statement has empty body.
警告:if语句有语句。
致命行为:
if (enable); // 由于";"语句的存在导致value的值一直不会刷新。
value = sum(i, j);
建议:
warning: division by zero is undefined.
警告:未定义被零除。
致命行为:
value = i / j; // 由于j变量可能为0值,严重会导致程序异常退出。
建议:
warning: variable 'value' is uninitialized when used here.
警告:变量"value"在这里使用时未初始化。
致命行为:
value
默认为0。导致难以想象的bug。int value;
if (value == 0) // 由于变量未确定初始值,则值不确定会导致判断有时会不进入。
enable = true;
建议:
=
作为比较warning: using the result of an assignment as a condition without parentheses.
警告:将赋值结果用作不带括号的条件。
use '==' to turn this assignment into an equality comparison.
使用'=='将该赋值转换为相等比较
致命行为:
if (i = 1) // 一直生效
enable = true;
if (i = 0) // 一直失效
enable = true;