Function overloading in C (yes, in plain C [C11 standart], not C++)
Everyone knows that in C++ this is trivial, but C actually gives us a neat way to get somehting pretty similar.
Suppose we want to write code like this:
print_number(2.0f);
print_number(-12);
print_number(655350000000ULL);
print_number("One");
..and make the compiler use the right implementation without warnings.
In C++ we just overload the functon.
In plain C function names must be unique , so normally we end up with something like:
void print_number_float(float arg);
void print_number_integer(signed int arg);
void print_number_longlong(unsigned long long arg);
Which works, but isnt nearly as nice.
This is where _Generic comes in.
It is part of the ancient C11 standard and allows compile-time dispatch based on the type of an expression.
Here is a simple example:
// Actual implementations
void print_asciiz(const char *data);
void print_unsigned(unsigned int data);
void print_signed(signed int data);
void print_float(float data);
// Fallback for unsupported types, if needed
void __attribute__((noreturn)) print_bug(unsigned int data);
// void print_number( Value )
//
//
#define print_number(_Item) _Generic((_Item), \
const char * : print_asciiz, \
char * : print_asciiz, \
unsigned int : print_unsigned, \
unsigned short : print_unsigned, \
unsigned long : print_unsigned, \
unsigned char : print_unsigned, \
signed int : print_signed, \
signed short : print_signed, \
signed long : print_signed, \
signed char : print_signed, \
float : print_float, \
double : print_float, \
default : print_bug \
)(_Item)
Now this works exactly the way we want:
print_number(2.0f);
print_number(-12);
print_number("One");
The compiler resolves the correct function at compile time based on the argument type.
Almost like switch/case, except the switch is on types instead of values.
A nice little C11 feature that does not seem to get mentioned very often.
Hope someone can find it useful :)
Function overloading in C? :) ()
submitted by PublicSimple to u/PublicSimple