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.
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.
As already stated, overloading in the sense that you mean isn't supported by C. A common idiom to solve the problem is making the function accept a tagged union. This is implemented by a
struct
parameter, where thestruct
itself consists of some sort of type indicator, such as anenum
, and aunion
of the different types of values. Example:This may not help at all, but if you're using clang you can use the overloadable attribute - This works even when compiling as C
http://clang.llvm.org/docs/AttributeReference.html#overloadable
Header
Implementation
I hope the below code will help you to understand function overloading
Normally 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:
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).
If your compiler is gcc and you don't mind doing hand updates every time you add a new overload you can do some macro magic and get the result you want in terms of callers, it's not as nice to write... but it's possible
look at __builtin_types_compatible_p, then use it to define a macro that does something like
but yea nasty, just don't
EDIT: C1X will be getting support for type generic expressions they look like this:
The following approach is similar to a2800276's, but with some C99 macro magic added: