1
#include <iostream>

using namespace std;

int square(int x);
float square(float x);

int main() {
    cout<<square(3);
    cout<<square(3.14);

    return 0;
}

int square(int x) {
    cout<<"\nINT version called\n";
    return x*x;
}

float square(float x) {
    cout<<"\nFLOAT version called\n";
    return x*x;
}

I have tried to replace the float version of a function with double one, and it starts to work then. What is the problem here? Cannot 3.14 be considered as float?

error: call of overloaded 'square(double)' is ambiguous
note: candidates are:
note: int square(int)
note: float square(float)

Siguza
  • 21,155
  • 6
  • 52
  • 89
realvadim
  • 154
  • 12
  • Convert to `(float)` or use `f` in your literal (`3.14f`) if you want to. I'd recommend using `double` though as it has more precision and it is the default floating point as mentioned [here](http://stackoverflow.com/questions/4353780/why-floating-point-value-such-as-3-14-are-considered-as-double-by-default-in-msv). – Zach P Jun 17 '15 at 08:38

2 Answers2

8

Floating-point literals in C++ are of type double. Conversions from double to int and float do not have an ordering defined, so your call is ambiguous.

If you want to call the float function, call it with a float literal:

cout<<square(3.14f);
//note the f here^
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
0

3.14 is taken as a double by the compiler . It does not find a function with double argument and is confused if it should convert the double to int or float .Therefore either try below code or use double in function declaration.

 cout<<square(3.14f);
Sourav Kanta
  • 2,727
  • 1
  • 18
  • 29