c/c++ unsigned类型的溢出问题

luuillu 2011-07-04 05:22:54
1.
c/c++中的unsigned 类型的变量发生溢出时,是舍掉溢出的部分,直接取低位部分作为结果,还是结果是未定义的?

如果:
unsigned a=0xffffffff;
unsigned b=a+3;

那么此时b=2,还是b的值是未定义的?

2.
无符号数作减法是否会发生溢出?
如果
unsigned a=1;
unsigned b=4;
那么
a-b 会溢出吗?
(我的理解是,因为a-b=-3超出了usined的表示范围,因此会发生溢出)

b-a 会溢出吗?
(我的理解是,因为在计算机中,减法是按补码计算的,所以b-a=4+(-1)=4+0xffffffff,这超出了usined的表示范围,因此也会溢出。)
...全文
422 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
ouwarmth 2011-07-04
  • 打赏
  • 举报
回复
学习了。。。
qq120848369 2011-07-04
  • 打赏
  • 举报
回复
暂且可以认为是舍弃二进制高位进行分析.
飞天御剑流 2011-07-04
  • 打赏
  • 举报
回复
溢出是有符号数的概念,无符号数是没有溢出的。

无符号数当发生超出其表示范围的行为时,其值是将其内部二进制表示以2的n次方(n为该无符号数的二进制长度)作模所得的余数,无论C还是C++都如此。

3.9.1 Fundamental types

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

41) 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.

pengzhixi 2011-07-04
  • 打赏
  • 举报
回复
1.标准规定溢出是未定义的行为

2.减法一样会溢出,溢出分上溢和下溢

64,649

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧