What exactly is std::labs() there for?

I read about the std::abs() function when browsing cppreference.

On that page I have also seen a std::labs() function. Which has the same prototype as one of the std::abs() overloads (the one for long).

long abs( long n );

long labs( long n );

and

long long abs( long long n );

long long llabs( long long n );

So,

  • What exactly std::labs() does?
  • Where and when do I use std::labs()?
  • What is the difference between std::abs() and std::labs()?

C++11 was when std::labs and std::llabs were added. This was part of the partial syncing done to the C++ standard library with the C99 standard library.

You don't really need it in C++ code, because we had a long overload of std::abs since about forever. But if you have some C code (that by sheer coincidence also compiles with a C++ compiler), and it uses labs, you can build it with a C++11 compiler and standard library.


In retrospect, there is one marginally useful use case for these functions. And that is when an attempt to use std::abs is ambiguous. For instance:

template<typename T>
T run_func(T (&f)(T)) {
  return f({});
}

Then trying to call run_func(std::abs); is ill-formed. We need to either specify the template argument explicitly or cast std::abs to the proper type. On the other hand run_func(std::labs); isn't ambiguous, and not too verbose.

Still, not too useful.