C++ Logo

std-proposals

Advanced search

std::nabs (negative abs) idea

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Fri, 12 Feb 2021 19:37:15 +0300
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.

Received on 2021-02-12 10:37:20