I’m recently introduced in the programming world and the C language.

I've encountered a trouble understanding the following concept when I tried to utilize the pow function from the math.h library, in order to do some calculations in my code.

While I passed as parameters to the pow function the two variables, x and i, both declared as integers, I got an Error from my IDE(Visual Studio 2012) stating

: “more than one instance of overloaded function “pow” matches the argument list" :

Function “pow(double _X, int _Y)”
Function “pow(float _X , int _Y)”
Function “pow(float _X , int _Y)”
Function “pow(long double _X, int _Y)”

Argument types are ( int, int ).

I know that the pow function returns a double value but what happens, let’s say when you need to work only with integers ? Why is it not possible to store the return value of the function to a declared variable as a double and having two integers as parameters?

Searching Wikipedia ,when I couldn't find anything relevant here in Stack Overflow, the only given definition for function overloading is the following one:

Function overloading or method overloading is a feature found in various programming languages such as Ada, C++, C#, D, and Java, that allows creating several methods with the same name which differ from each other in the type of the input and the output of the function. It is simply defined as the ability of one function to perform different tasks. “

What is function overloading exactly and how it affects the behavior of this particular function that I try to implement ?

Sorry in advance if the question is too trivial or answered, or I’m missing an obvious piece of the puzzle .

有帮助吗?

解决方案

You are using a C++ compiler, there is no function overloading in (classic) C.

There, we have different functions for those cases (see the manual page here):

  • double pow(double x, double y);
  • float powf(float x, float y);
  • long double powl(long double x, long double y);

So it's always clear from the function name what the types involved are.

Since the C99 version of C, you can use generics to implement this, and it's already done in the <tgmath.h> header. This header gives you a function pow() which uses overloading.

It's pretty clear from your error output that you don't have such a C compiler, though.

其他提示

No function overloading in C.
The only overloading in C is operator overloading in the compiler (int + int , float + float, & as adress-of, & as bitwise-and, * as pointer-to, * as multipy...).

You can't overload a function. But if you are using double, int, short, long, float you can do a single function and pass casted argument.

double  pow(double, double);

int a;
int b;

int c = (int)pow((double)a, (double)b);

You have to take the largest type possible. it's a simple trick with the compiler.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top