Overloaded functions

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?

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. :slight_smile:

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.

IMHO, no one would ever want to work with floating point at all in an embedded system like this. It makes no sense.

JMHO…

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.