gpt4 book ai didi

c - 转换未更改值时发出警告

转载 作者:太空宇宙 更新时间:2023-11-04 03:29:21 25 4
gpt4 key购买 nike

考虑这个程序:

int main() {
int ju = 1;
short ki = ju;
return ki;
}

编译产生警告:

conversion to ‘short int’ from ‘int’ may alter its value [-Wconversion]
short ki = ju;
^

然而根据to the docs :

Do not warn [...] if the value is not changed by the conversion like in "abs (2.0)".

我们正在处理1的值,它可以很容易地存储在int。该值未因转换而更改,那么为什么会出现警告?

最佳答案

忽略任何可能的编译器优化:

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 的值是多少,因此它会正确地警告隐式类型转换。

关于文档,并引用您的问题:

Do not warn [...] if the value is not changed by the conversion like in "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) 示例)。

关于c - 转换未更改值时发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38287363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com