vsoftco vsoftco - 2 months ago 9
C++ Question

Why is there a `std::llabs`?

Looking at the

std::abs
overloads form
cppreference
, I realized that there are two different functions that do the exact same thing, both being introduced in C++11:

long long abs( long long n );


and

long long llabs( long long n );


Is there any reason why
std::llabs
was introduced? Because of possible ambiguities? (although I think the later can be resolved via a simple cast).

Answer

It's for C source compatibility. C doesn't have function overloading (sans some magic macros using _Generic from C11).

So, if you want your code to compile in both C and C++ modes, i.e. as some kind of library, you can do the following and have the code compile successfully in both C++ and C modes.

// foo.c
#include <stdlib.h>

#ifdef __cplusplus
extern "C"
#endif
long long foo(long long val) {
    return llabs(some_value);
}

If you were to call abs in the above snippet, different functions would've been called in C and C++ modes.