C++ Logo


Advanced search

Re: std::nabs (negative abs) idea

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Fri, 12 Feb 2021 20:52:51 +0300
On 2/12/21 8:50 PM, Magnus Fromreide wrote:
> On Fri, Feb 12, 2021 at 08:14:31PM +0300, Andrey Semashev via Std-Proposals wrote:
>> On 2/12/21 7:58 PM, Brian Bi via Std-Proposals wrote:
>>> What are the use cases for this function?
>>> I guess a potentially overflowing `x + abs(y)` could be replaced by `x -
>>> nabs(y)`, but the overall result could still overflow...
>> One practical use case I had when I had this idea is when I wanted to select
>> a value that is closest to zero. A naive way to do this would be:
>> int select_closest_to_zero(int x, int y)
>> {
>> if (std::abs(x) < std::abs(y))
>> return x;
>> else
>> return y;
>> }
>> To avoid potential signed overflow I had to devise nabs().
>> I think, nabs() would be useful wherever abs() is used to bring multiple
>> values to the same sign, when the sign itself is not important or can be
>> compensated for by the surrounding code.
> I think nabs would be confusing in practice.
> A primary indicator of this is that you managed to get the test in
> select_closest_to_zero wrong.

It is not wrong. The code above uses abs(). With nabs() the comparison
would be reversed.

Received on 2021-02-12 11:52:56