由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - unsigned int subtract int
相关主题
pointer overflow有没有什么简单的方法从一个double precision的floating point 中读出一个特定的bit?
a question about bitwise operation一个hash table的简单问题
[合集] 编译报错stack overflow,到底来自何处关于Dword 和 word
借人气问个c++的overflow (转载)C++中size_type怎么处理?
经典题atoi的溢出处理 (转载)What is size_t mean in C?
一个integer promotion问题Any possibility to make this expression faster?
问一个在C里面转换十六进制的问题这个面试题有什么trick?
一道面试题[合集] reinterpret_cast a 4 byte unsigned char to integer
相关话题的讨论汇总
话题: 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版参与讨论
相关主题
[合集] reinterpret_cast a 4 byte unsigned char to integer经典题atoi的溢出处理 (转载)
[合集] 讨厌的WARNING: 在 MANAGED C++ 中写东东一个integer promotion问题
C++ 初学者请教一个 iostream 的问题问一个在C里面转换十六进制的问题
C++怎么写任意重重循环?一道面试题
pointer overflow有没有什么简单的方法从一个double precision的floating point 中读出一个特定的bit?
a question about bitwise operation一个hash table的简单问题
[合集] 编译报错stack overflow,到底来自何处关于Dword 和 word
借人气问个c++的overflow (转载)C++中size_type怎么处理?
相关话题的讨论汇总
话题: int话题: unsigned话题: subtract话题: write话题: overflow