不,这没有意义。
如果您想要差异,请使用
c = (a > b) ? a - b : b - a;
or
c = max(a, b) - min(a, b);
Unsigned if go below zero would wrap back (effect is similar to adding 2sizeof (unsigned long) * CHAR_BIT)
如果您正在寻找两个数字之间的差异,您可以编写一个小模板,如下所示
namespace MyUtils {
template<typename T>
T diff(const T&a, const T&b) {
return (a > b) ? (a - b) : (b - a);
}
}
看看声明abs http://en.cppreference.com/w/cpp/numeric/math/abs继承自C
(因为你包括了stdlib.h
)
int abs( int n );
long abs( long n );
long long abs( long long n ); // (since C++11)
//Defined in header <cinttypes>
std::intmax_t abs( std::intmax_t n ); // (since C++11)
And abs http://en.cppreference.com/w/cpp/numeric/math/fabs in C++
(from cmath
)
float abs( float arg );
double abs( double arg );
long double abs( long double arg );
如果您注意到,每个函数的参数和返回类型都是signed
。因此,如果将无符号类型传递给这些函数之一,则隐式转换unsigned T1 -> signed T2 -> unsigned T1
将发生(其中T1
and T2
可能相同并且T1
is long
在你的情况下)。当您将无符号整数转换为有符号整数时,如果无法以有符号类型表示,则该行为取决于实现。
From 4.7 积分转换[conv.integral]
- If the destination type is unsigned, the resulting value is the least
unsigned integer congruent to the source integer (modulo 2n where n is
the number of bits used to represent the unsigned type). [ Note: In a
two’s complement representation, this conversion is conceptual and
there is no change in the bit pattern (if there is no truncation). —
end note]
- 如果目标类型是有符号的,则如果可以的话,该值不会改变
以目标类型(和位字段宽度)表示;否则,
该值是实现定义的。