Whenever I run this code...
#include <iostream>
int add(int x, int y){
return x+y;
}
float add(float x, float y){
return x+y;
}
int main(){
using namespace std;
add(1.11, 1.11);
return 0;
}
... I get this error:
18.cpp: In function ‘int main()’:
18.cpp:24:16: error: call of overloaded ‘add(double, double)’ is ambiguous
add(1.11, 1.11);
^
18.cpp:24:16: note: candidates are:
18.cpp:7:5: note: int add(int, int)
int add(int x, int y){
^
18.cpp:11:7: note: float add(float, float)
float add(float x, float y){
I thought 1.11 would be clearly a float, not an integer. When I change float
to double
, the program works.
Why does C++ say the call is ambiguous?
In C++ the type of decimal literals like 1.11
is defined to be double. Given that it has to convert the double to either int
or float
which results in the ambiguity.
A literal with an f
suffix like 1.11f
would have type float.