20

In the following code snippets, In function call f(1), 1 is a literal of type int and in first function void f(double d) argument type is double and second function void f(short int i) argument type is short int.

Here 1 is an int type not a double type, then Why does compiler generated ambiguous error?

#include <iostream>
using namespace std;

void f(double d)  // First function
{
    cout<<d<<endl;
}

void f(short int i) // Second function
{
    cout<<i<<endl;
}

int main()
{
    f(1); // 1 is a literal of type int
    return 0;
}
Jayesh
  • 4,755
  • 9
  • 32
  • 62
  • 7
    Possible duplicate of [Why is it ambiguous to call overloaded ambig(long) and ambig(unsigned long) with an integer literal?](https://stackoverflow.com/questions/8771409/why-is-it-ambiguous-to-call-overloaded-ambiglong-and-ambigunsigned-long-with) – JHBonarius Sep 21 '17 at 07:23
  • 1
    I.e. "1 is an int type and short int is also int type" is an incorrect statement. – JHBonarius Sep 21 '17 at 07:44
  • 5
    `int` and `short int` are different types. `short` is not some sort of qualifier for `int` – M.M Sep 21 '17 at 07:54

1 Answers1

35

Because, as your comment notes, 1 is a literal of type int.

To the compiler, an implicit conversion of int to short int is equally as valid as an implicit conversion of int to double (cf. the C++ language standard, §13.3).

Thus, because the compiler can't decide between the double and short int overloads, it gives up and issues a diagnostic.

Note that the magnitude of the function parameter doesn't matter: just the type.

(It would be annoying if the compiler chose, at runtime, the short int overload if the calling argument was appropriate, and the double one in other instances.)

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Regarding your last sentence, it is a bit ironic that ``f(0)`` can indeed cause a different overload resolution than ``int a=0; f(a);``. But that's why ``nullptr`` was added, of course. – Arne Vogel Sep 22 '17 at 09:28