gpt4 book ai didi

c - 32 位系统中的无符号短整型提升

转载 作者:行者123 更新时间:2023-11-30 15:16:23 25 4
gpt4 key购买 nike

我有一个 32 位整数大小

如果我有一个像这样的算术表达式

unsigned short current_time, last_time
if((current_time - last_time) > timeout)

我相信current_time和last_time在减法之前都会被转换为signed int 32。 16 位整数大小系统没有问题,但是对于 32 位整数大小系统,是否会因为整数提升而出现负值?

最佳答案

如果current_time大于或等于last_time,则不会出现负值。

引用 C90 规范第 6.2.1.2 节“有符号和无符号整数”:

When a value with integral type is converted to another integral type, if the value can be represented by the new type, its value is unchanged.

由于unsigned Shortint短,所有unsigned Short类型的值都可以用int表示,因此 current_timelast_time 转换为 int 值将与其未转换的 unsigned Short 相同code> value,减法的结果将是您期望的结果。

但是,如果 current_time 小于 last_time,则可能会出现负值;然而,这不是一个错误,而是一个功能,因为在这种情况下,时间确实确实倒退了。

如果current_timelast_timeunsigned int,并且current_time小于last_time,减法的结果将是一个 unsigned int,因此不是负数;它是时间之间的差值,以 unsigned int 的最大值为模。

无论如何,如果可能的话,您可能想专门处理时间倒退的情况。

关于c - 32 位系统中的无符号短整型提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33116497/

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