Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to achieve function overloading in C?

Is there any way to achieve function overloading in C? I am looking at simple functions to be overloaded like

foo (int a)  
foo (char b)
foo (float c , int d)


I think there is no straight forward way; I'm looking for workarounds if any exist.
by

3 Answers

aashaykumar
There are few possibilities:

1.printf style functions (type as an argument)
2. opengl style functions (type in function name)
3. c subset of c++ (if You can use a c++ compiler)
pankajshivnani123
In the sense you mean — no, you cannot.

You can declare a va_arg function like

void my_func(char* format, ...);

But you'll need to pass some kind of information about number of variables and their types in the first argument — like printf() does.
kshitijrana14
ormally a wart to indicate the type is appended or prepended to the name. You can get away with macros is some instances, but it rather depends what you're trying to do. There's no polymorphism in C, only coercion.

Simple generic operations can be done with macros:

#define max(x,y) ((x)>(y)?(x):(y))

If your compiler supports typeof, more complicated operations can be put in the macro. You can then have the symbol foo(x) to support the same operation different types, but you can't vary the behaviour between different overloads. If you want actual functions rather than macros, you might be able to paste the type to the name and use a second pasting to access it (I haven't tried).

Login / Signup to Answer the Question.