C++ Logo


Advanced search

Subject: Re: [std-proposals] std::nabs (negative abs) idea
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2021-02-12 11:14:31

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;
       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.

> On Fri, Feb 12, 2021 at 11:37 AM Andrey Semashev via Std-Proposals
> <std-proposals_at_[hidden] <mailto:std-proposals_at_[hidden]>>
> wrote:
> Hi,
> I've been contemplating a possible new standard function std::nabs,
> which would return a negated absolute value of its argument:
>    assert(std::nabs(1) == -1);
>    assert(std::nabs(-1) == -1);
>    assert(std::nabs(0) == 0);
> The idea behind this addition is that, unlike std::abs, this function
> will never cause a signed integer overflow. This is because in two's
> complement representation, which is mandatory since C++20, any positive
> integer can be negated without overflow, but not vise versa.
> I wonder if this idea has come up before.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden] <mailto:Std-Proposals_at_[hidden]>
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
> <https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals>
> --
> /Brian Bi/

STD-PROPOSALS list run by std-proposals-owner@lists.isocpp.org

Standard Proposals Archives on Google Groups