I'd like to write some functions in C but they have to be available for all numeric types (int, float, double). What is good practise? Use pointer on void (and pointer to function of course)? Or write a different function for every type?
For example:
float func(float a, float b) {
return a+b;
}
If you can use C11, _Generic can help:
#include <stdio.h>
int ifunc(int a, int b) { return a+b; }
float ffunc(float a, float b) { return a+b; }
double dfunc(double a, double b) { return a+b; }
#define func(x, y) \
_Generic((x), int: ifunc, float: ffunc, double: dfunc, default: ifunc)(x, y)
int main(void)
{
{
int a = 1, b = 2, c;
c = func(a, b);
printf("%d\n", c);
}
{
float a = .1f, b = .2f, c;
c = func(a, b);
printf("%f\n", c);
}
{
double a = .1, b = .2, c;
c = func(a, b);
printf("%f\n", c);
}
return 0;
}
As C does not have multiple dispatch (function overloading) like C++ (EDIT: unless you use C11, which has _Generic) , you have to name the functions for each type differently, like funcInt(int a, int b); funcFloat(float a, float b);
OR
use GCC style statement-expression macros which allow typeof()
to kind of fake it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With