abs(unsigned long) 有任何意义吗?

2024-01-08

我遇到过这段代码,我的分析器偶然将其报告为瓶颈:

#include <stdlib.h>

unsigned long a, b;
// Calculate values for a and b
unsigned long c;

c = abs(a - b);

那条线有什么更有趣的事情吗c = a - b;?这两个选项是否会调用未定义或实现定义的行为,是否还有其他潜在的问题?请注意,C<stdlib.h>包含在内,不包含<cstdlib>.


不,这没有意义。

如果您想要差异,请使用

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]

  1. 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]
  2. 如果目标类型是有符号的,则如果可以的话,该值不会改变 以目标类型(和位字段宽度)表示;否则, 该值是实现定义的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

abs(unsigned long) 有任何意义吗? 的相关文章

随机推荐