C++ Logo

STD-PROPOSALS

Advanced search

Subject: Re: [std-proposals] std::nabs (negative abs) idea
From: Magnus Fromreide (magfr_at_[hidden])
Date: 2021-02-12 11:50:10


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.

/MF


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

Standard Proposals Archives on Google Groups