2

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?

Username
  • 3,463
  • 11
  • 68
  • 111
  • 5
    `I thought 1.11 would be clearly a float,` No, literals like 1.11 are `double`s by default. A conversion has to happen either way, and now the compiler is unsure which one. – deviantfan Jan 23 '16 at 05:59
  • I thought both floats and doubles can hold two decimal places? – Username Jan 23 '16 at 06:01
  • 1
    While your value could go into a float without problems, it's just the way the language works. A literal like 1.11 is double just because it has a decimal part (ie. not int), unless you say explicitly that it is a float – deviantfan Jan 23 '16 at 06:02
  • 1
    @Username "floats and doubles" those are different types. "hold two decimal places" [Nope](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Ivan Aksamentov - Drop Jan 23 '16 at 06:03
  • 1
    [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) | [The Definitive C Book Guide and List](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) – Ivan Aksamentov - Drop Jan 23 '16 at 06:04
  • 1
    Or http://en.cppreference.com/w/cpp/language/floating_literal – deviantfan Jan 23 '16 at 06:04
  • 1
    you can call `add(1.11f, 1.11f)` instead to let compiler know you want to call `add(float, float)`. – triple_r Jan 23 '16 at 06:05
  • 1
    I *think* you can even call 'add(11.1f, 11.1)' and the compiler can figure it out. – Martin Bonner supports Monica Jan 23 '16 at 08:26

1 Answers1

5

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188