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?
|
|