gpt4 book ai didi

c++ - INT_MIN/-1 是 C++ 中定义的行为吗?

转载 作者:太空狗 更新时间:2023-10-29 23:52:09 30 4
gpt4 key购买 nike

我有以下 INT_MIN/-1 代码。我希望这会变成 INT_MAX+1(或翻转时为 0)。然而,我得到的实际结果是 INT_MIN。这是我的测试代码:

#define __STDC_LIMIT_MACROS
#include <stdint.h>
#include <stdio.h>
#include <limits.h>
using namespace std;
int main()
{
int min=INT_MIN;
int res=min/-1;
printf("result: %i\n", res);
printf("max: %i min: %i\n", INT_MAX, INT_MIN);
return 0;
}

这个实现是特定的和/或未定义的行为吗?

最佳答案

Is this implementation specific and/or undefined behavior?

是的,signed 整数溢出是未定义的行为。根据 C++11 标准的第 5/4 段:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [...]

注意,这同样不适用于无符号算术。如第 3.9.1/4 段和脚注 46 中所述:

Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of that particular size of integer. [...]

This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.

关于c++ - INT_MIN/-1 是 C++ 中定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17176221/

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