gpt4 book ai didi

c++ 只有 : unary minus for 0x80000000

转载 作者:太空狗 更新时间:2023-10-29 20:16:27 26 4
gpt4 key购买 nike

这个问题应该是给语言律师的。

假设 signed 和 unsigned int 都是 32 位宽。如 n3337.pdf 草案 5.3.1.8 所述,

(-(0x80000000u)) = 0x100000000u-0x80000000u = 0x80000000u

但我找不到问题的答案:signed 0x80000000 的一元减号是什么?是 UB、实现定义还是...?

问题主要是关于运行时计算。

   signed int my_minus(signed int i) { return -i;}
....
int main() {
signed int a = -0x7FFFFFFF; // a looks like 0x80000001
signed int b = a - 1; // b looks like 0x80000000
std::cout << my_minus(b);
....
}

不过,欢迎您对其他 2 个案例发表评论:

  • 编译时常量折叠,比如 -(INT_MIN)

  • constexpr 的编译时计算(如果与编译时常量折叠有区别)。


(请在重复投票前查看https://meta.stackexchange.com/questions/123713/is-splitting-a-question-a-good-practice。)

最佳答案

据我所知,有符号整数溢出总是未定义的。来自 C++ 规范部分 5 Expressions,第 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. [Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. —endnote]

关于c++ 只有 : unary minus for 0x80000000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9476036/

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