Log in

View Full Version : Overloaded functions


jgannon
30-12-2004, 19:03
In my header file, I have the following function prototypes:

int abs(int);
float abs(float);

In my source file, I have the following functions:

int abs(int x)
{
if(x>=0)
return x;
else
return -x;
}

float abs(float x)
{
if(x>=0)
return x;
else
return -x;
}

I also have a whole bunch of other overloaded functions. (I know this isn't the best example, but it's short.) However, when I compile it, I get a lot of "type mismatch in redeclaration of 'abs'" and "redefinition of 'abs'" errors. Does the C18 compiler not support overloading, or am I doing something wrong that I'm overlooking?

Max Lobovsky
30-12-2004, 19:05
If I'm not mistaken, overloadable functions was added in C++ and is not possible in C.

jgannon
30-12-2004, 19:08
If I'm not mistaken, overloadable functions was added in C++ and is not possible in C.
Hm... that's unfortunate. Is there any way to get the equivalent of overloading, without making two separately named functions? I guess this is what happens when a TI-BASIC/C++/Java programmer tries to do C. :)

Max Lobovsky
30-12-2004, 19:18
Well for this example, you could easily just cast to int and use the same function. (You could cast to int in all cases, even when it already is an int, to maintain uniformity). I can't really think of any other way.

Mike Betts
30-12-2004, 22:51
IMHO, no one would ever want to work with floating point at all in an embedded system like this. It makes no sense.

JMHO...

Astronouth7303
31-12-2004, 11:04
The only thing I can think of is to use a macro

#define ABS(num) ( ((num) >= 0) ? (num) : (0 - (num)) )

which will work for any numeric type you give it.

But I still wouldn't use floating point.