考虑一下这个项目:
int main() {
int ju = 1;
short ki = ju;
return ki;
}编译会产生一个警告:
conversion to ‘short int’ from ‘int’ may alter its value [-Wconversion]
short ki = ju;
^然而,根据去医生那里
别警告..。如果值未被转换更改,如"abs (2.0)“中所示。
我们正在处理1的值,它可以很容易地存储在int或short中。值不被转换更改,那么为什么要发出警告呢?
发布于 2016-07-10 00:40:30
忽略任何可能的编译器优化:
int main() {
int ju = 1;
short ki = ju; /* Compiler won't [probably] make use of (without optimizations) what the value of ju is at runtime */
return ki;
}另一个示例(即使对编译器进行优化,也无法确定在编译时将ju分配给ki时的值):
int foo() {
int ju = 1;
short ki = 1;
scanf("%d", &ju);
ki = ju; /* (Compiler will issue the warning) What's the value of ju? Will it fit in ki? */
return ki; /* Another implicit conversion, this one from short to int, which the compiler won't issue any warning */
}编译器无法知道ju的值,因此它正确地警告了隐式类型转换。
关于文件,并引用你的问题:
别警告..。如果值未被转换更改,如"abs (2.0)“中所示。
int foo() {
return 0UL;
}这是一个例子,不管涉及的类型如何,值都不会改变。零将永远是零,因为它是int或unsigned long类型。
或,
int foo() {
return 2.0; /* Same case as abs(2.0), an implicit float to int convertion, whose values are not changed by doing so. */
}因此,基本上,这只适用于文本(例如文档中给出的abs(2.0)示例)。
发布于 2016-07-10 01:06:24
short ki = ju;落在
可能更改值1的隐式转换。
就可以存储的位数而言,int几乎总是大于short。这是已知的编译时。
值不被转换更改,那么为什么要发出警告呢?
这是你凭直觉得出的结论。这一知识,即使已知需要not2,也要使用编译时。
参考
[1] gcc警告选项。
Note
2编译器不需要跟踪存储在变量中的值。
https://stackoverflow.com/questions/38287363
复制相似问题