0

Hi All,

I have a question about the following C++ program:
How does the C++ program know which of the sqr functions to use in this program?

#include <iostream.h>
// This program illustrate the use of Function overloading
int sqr(int x);
float sqr(float x);
double sqr(double x);

int main(void)
{ // declare three variable of different types
int val1=4;
float val2=4.1;
double val3=4.123456;
// get the data from the user and call each version of function
cout << "Square of 4 is " << sqr(val1) << "\n";
cout << "Square of 4.1 is " << sqr(val2) << "\n";
cout << "Square of 4.123456 is" << sqr(val3) << "\n";
return(0);
}
// now declare the three function versions
int sqr(int x) {
return(x*x);
}

float sqr(float x) {
return(x*x);
}
double sqr(double x) {
return(x*x);
}
3
Contributors
2
Replies
4
Views
10 Years
Discussion Span
Last Post by thekashyap
0

It matches the type you use when you call it to choose the correct one.

Btw, <iostream.h> is deprecated. Use <iostream> instead. ;)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.