C++ Logo

std-proposals

Advanced search

Re: std::nabs (negative abs) idea

From: Brian Bi <bbi5291_at_[hidden]>
Date: Fri, 12 Feb 2021 11:58:43 -0500
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...

On Fri, Feb 12, 2021 at 11:37 AM Andrey Semashev via Std-Proposals <
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]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>


-- 
*Brian Bi*

Received on 2021-02-12 10:58:57