加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c only:一元减去0x80000000

发布时间:2020-12-16 09:40:48 所属栏目:百科 来源:网络整理
导读:据推测,这个问题适用于语言律师. 假设signed和unsigned int都是32位宽.如n3337.pdf草案中所述,5.3.1.8, ( – (0x80000000u))= 0x100000000u-0x80000000u = 0x80000000u 但是我找不到问题的答案:对于签名的0x80000000,什么是一元减去?它是UB,实现定义还是…
据推测,这个问题适用于语言律师.

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

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

但是我找不到问题的答案:对于签名的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节表达式,第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]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读