Search code examples
c++cmath

How to fix "error: call to 'abs' is ambiguous"


I'm running a simple C++ program from HackerRank about pointers and it works fine on the website. However, when I run it on MacOS, I get error: call to 'abs' is ambiguous and I'm not sure exactly what is ambiguous.

I've looked at other answers to similar issues, but the error message tends to be Ambiguous overload call to abs(double), which is not the issue I'm having, since I haven't used any doubles. I've also tried including the header files cmath and math.h, but the problem persists.

#include <stdio.h>
#include <cmath>

void update(int *a,int *b) {
    int num1 = *a;
    int num2 = *b;
    *a = num1 + num2;
    *b = abs(num1 - num2);
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;

    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}

My issue occurs with line 8.


Solution

  • The full error message is:

    $ clang++ test.cpp
    test.cpp:8:10: error: call to 'abs' is ambiguous
        *b = abs(num1 - num2);
             ^~~
    .../include/c++/v1/math.h:769:1: note: candidate function
    abs(float __lcpp_x) _NOEXCEPT {return ::fabsf(__lcpp_x);}
    ^
    .../include/c++/v1/math.h:769:1: note: candidate function
    abs(double __lcpp_x) _NOEXCEPT {return ::fabs(__lcpp_x);}
    ^
    .../include/c++/v1/math.h:769:1: note: candidate function
    abs(long double __lcpp_x) _NOEXCEPT {return ::fabsl(__lcpp_x);}
    ^
    1 error generated.
    

    The three overloads of abs that you have from <cmath> are abs(float), abs(double) and abs(long double); it's ambiguous because you have an int argument and the compiler doesn't know which floating-point type to convert to.

    abs(int) is defined in <cstdlib>, so #include <cstdlib> will resolve your problem.

    If you're using Xcode, you can get more details about the error in the Issues navigator (⌘5) and clicking the triangle next to your issue.