gpt4 book ai didi

c++ - 比较一个长变量与INT_MAX + 1

转载 作者:行者123 更新时间:2023-12-01 15:11:09 24 4
gpt4 key购买 nike

//Code here
long a = 42;
if(a > INT_MAX + 1)

当我进行比较时, a > INT_MAX + 1实际上返回true,这使我感到困惑。
原因似乎是 INT_MAX + 1溢出了。但为什么? INT_MAX应该只是由像 2^32 - 1这样的常量定义的宏,因此 INT_MAX + 1应该只是另一个常量值 2^32。而且由于 a很长,因此在编译期间,编译器还应隐式将 INT_MAX + 1转换为long类型,该类型应长于int且不会溢出。

我不明白为什么它实际上溢出了。

有人可以帮我吗?非常感谢。

最佳答案

therefore INT_MAX + 1 should be just another constant value



这是一个算术表达式。更具体地说,它是加法运算。添加溢出,并且程序的行为未定义。

therefore during compiling the compiler should also implicitly convert the INT_MAX + 1 to long type



是的但是结果的转换发生在操作之后。

您可以使用 a - 1 > INT_MAX修复表达式。尽管当 ALONG_MIN时也有失败的情况。另一种方法是将加法运算符之一转换为较大的类型(如果系统上存在较大的类型)。

关于c++ - 比较一个长变量与INT_MAX + 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59523352/

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