boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - unsigned int subtract int
相关主题
pointer overflow
a question about bitwise operation
[合集] 编译报错stack overflow,到底来自何处
借人气问个c++的overflow (转载)
经典题atoi的溢出处理 (转载)
一个integer promotion问题
问一个在C里面转换十六进制的问题
一道面试题
有没有什么简单的方法从一个double precision的floating point 中读出一个特定的bit?
一个hash table的简单问题
相关话题的讨论汇总
话题: int话题: unsigned话题: subtract话题: write话题: overflow
进入Programming版参与讨论
1 (共1页)
x**e
发帖数: 96
1
in C/C++, what is the most portable way to subtract an int from unsigned int?
int a;
unsigned b;
a could be either positive or negative,
b>0 and cannot be represented by int (may overflow)
and I know b>abs(a) and b+abs(a) will not overflow in unsigned int.
is it safe and portable to write
b-=a;
or what is the best way to write it?
t****t
发帖数: 6806
2
yes it is ok to write that way. int will be converted to unsigned and the
result is unsigned. negative number can be automatically handled (wrap
around).
but most compiler will issue a warning against this case (if the warning
level is high -- which is recommended). so you better write
b-=(unsigned)a;

int?

【在 x**e 的大作中提到】
: in C/C++, what is the most portable way to subtract an int from unsigned int?
: int a;
: unsigned b;
: a could be either positive or negative,
: b>0 and cannot be represented by int (may overflow)
: and I know b>abs(a) and b+abs(a) will not overflow in unsigned int.
: is it safe and portable to write
: b-=a;
: or what is the best way to write it?

1 (共1页)
进入Programming版参与讨论
相关主题
一个hash table的简单问题
关于Dword 和 word
C++中size_type怎么处理?
What is size_t mean in C?
Any possibility to make this expression faster?
这个面试题有什么trick?
[合集] reinterpret_cast a 4 byte unsigned char to integer
[合集] 讨厌的WARNING: 在 MANAGED C++ 中写东东
C++ 初学者请教一个 iostream 的问题
C++怎么写任意重重循环?
相关话题的讨论汇总
话题: int话题: unsigned话题: subtract话题: write话题: overflow