In the code I am writing I need a foo(int, char*)
and a foo(int, int)
functions.
If I was coding this in C++ I would use templates. Is there any equivalent for C? Or should I use void pointers? How?
Thanks.
In the code I am writing I need a foo(int, char*)
and a foo(int, int)
functions.
If I was coding this in C++ I would use templates. Is there any equivalent for C? Or should I use void pointers? How?
Thanks.
You can't do that.
In C there are no overloads, one function, one name, you'll need to use a type that supports all your needs, e.g. (void *)
Either that or do a foo_int(int,int)
and a foo_char(int, char*)
I think the closest you can get in C to templates is some ugly macro code. For example, to define a simple function that returns twice its argument:
#define MAKE_DOUBLER(T) \
T doubler_##T(T x) { \
return 2 * x; \
}
MAKE_DOUBLER(int)
MAKE_DOUBLER(float)
Note that since C doesn't have function overloading, you have to play tricks with the name of the function (the above makes both doubler_int
and doubler_float
, and you'll have to call them that way).
printf("%d\n", doubler_int(5));
printf("%f\n", doubler_float(12.3));
Others have discussed the intrinsic limitation of c with regard to overloading. Note, however, that if you can deduce which case is needed you can use varargs:
#include <stdarg.h>
foo(int, ...);
If you can't deduce it, you can pass an extra argument:
foo(int, char *spec, ...);
where spec
tells the function what to expect in the subsequent arguments. Like the printf
and scanf
families of functions. In fact, you might find it convenient to reuse the printf/scanf conventions for specifying type, thus saving your users from having to lean another mini-language.