gpt4 book ai didi

c - 可能不一致的类型转换行为

转载 作者:太空狗 更新时间:2023-10-29 15:05:59 25 4
gpt4 key购买 nike

GCC 4.8.0 编译为 32 位。

我发现案例 26 的行为令人困惑:

int16_t s16 = 0;
double dbl = 0.0;

s16 = (int16_t)((double)32767.0); // 1: s16 = 32767
s16 = (int16_t)((double)32768.0); // 2: s16 = 32767
s16 = (int16_t)((double)-32768.0); // 3: s16 = -32768
s16 = (int16_t)((double)-32769.0); // 4: s16 = -32768

dbl = 32767.0;
s16 = (int16_t)dbl; // 5: s16 = 32767
dbl = 32768.0;
s16 = (int16_t)dbl; // 6: s16 = -32768
dbl = -32768.0;
s16 = (int16_t)dbl; // 7: s16 = -32768
dbl = -32769.0;
s16 = (int16_t)dbl; // 8: s16 = -32768

我意识到它是实现定义的,但一致性仍然很好。谁能解释一下这是怎么回事?

最佳答案

根据 6.3.1.4 (1),行为不是实现定义的,它是未定义的:

If the value of the integral part cannot be represented by the integer type, the behavior is undefined.61)

61) The remaindering operation performed when a value of integer type is converted to unsigned type need not be performed when a value of real floating type is converted to unsigned type. Thus, therange of portable real floating values is (−1, Utype_MAX+1).

该段落在 C99 中是相同的,只是脚注的编号不同 (50)。

对于未定义的行为,编译时求值的表达式行为与运行时求值的行为不同的情况并不少见,例如

1 << width_of_type

如果移动距离作为常量表达式给出,则通常评估为 0,如果它是运行时值,则评估为 1。

据我所知,导致相同代码出现不同行为的原因是,由于未定义行为是编译器生成任何内容的许可,它也可能做最简单和/或最快的事情,编译期间最简单/最快的事情可能与运行时最简单/最快的事情不同。

关于c - 可能不一致的类型转换行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16040184/

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