Search code examples
c++type-conversionoverloadingambiguous-call

`long` and `double` are same when converting from `int ` by compiler


I was studying function overloading in c++, and I saw an ambiguous condition, in the program,

long add(long a){
    long b = a;
    return b;
}

double add(double a){
    double b = a;
    return b;
}

int main(){
    int x;
    x = add(10);
    printf("x : %d", x);
    getch();
    return 0;   
}

The reason of ambiguity given in the book was, the compiler may convert int either in long or in double. So compiler generates an error. I run this and the result was same, error.

So how long and double are equivalent? what's the actual reason of ambiguity here?


Solution

  • It is not that long and double are equivalent in themselves, but rather the conversion rules int->long and int->double have equivalent priority, so the compiler faces an ambiguity in the presence of both options.