NetBSD-Users archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

C++ language lawyer Q: requirements for bare abs()?



I recently had trouble with code in proj, which used abs() from C++,
expecting it to be double instead of int.  Changing to std::abs() fixed
it.

That brought up the question of what the rules are.  In C, abs() is
solidly integer:

     #include <stdlib.h>

     int
     abs(int x);

and there is fabs()

     #include <math.h>

     double
     fabs(double x);

But C++ is different.  The standard approach is <cmath> and std::abs(),
but I find claims that C++11 requires that <cmath> make (bare) abs()
overloaded, and claims that C++11 permits but does not require it.

In practice, it seems clear that the only reasonable coding approach is
to include <cmath> and then use std::abs() but the standards question
remains.

I found a test program, enhanced it, and ran it on 5 systems, with
varying results.

Is NetBSD wrong here?   Or is not overloading abs() permissible?
Is Debian wrong?


----------------------------------------
/*
 * This program tests if using bare abs() in C++ on a double is an
 * integer or floating point abs.
 *
 * The Internet is conflicted over whether <cmath> MAY or SHALL provide overloads.
 *
 * https://stackoverflow.com/questions/21392627/abs-vs-stdabs-what-does-the-reference-say
 * https://cplusplus.com/reference/cmath/abs/
 * https://github.com/OSGeo/PROJ/pull/4486
 */

#include <iostream>

//#include <math.h>
//#include <cmath>

int main(int argc, const char * argv[])
{
  double x = -1.5;
  double ax = abs(x);
  double sax = std::abs(x);
  std::cout << "x=" << x << " ax=" << ax << " sax=" << sax << std::endl;
  return 0;
}

/*
c++ -Wall cpp_abs.cpp; ./a.out

		none	math.h	cmath	both	both/R
 NetBSD/gcc7	1	1	1	1	1
 NetBSD/gcc10	1	1	1	1	1
 Debian/gcc12	1	1.5	1	1.5	1.5
 macOS 10.13	DNC	DNC	1.5	1.5	1.5
 macOS 13	1.5	1.5	1.5	1.5	1.5

*/




Home | Main Index | Thread Index | Old Index