Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C multiple types function

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;
 }
like image 534
Joseph89 Avatar asked Dec 24 '22 10:12

Joseph89


2 Answers

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;
}
like image 118
David Ranieri Avatar answered Dec 26 '22 22:12

David Ranieri


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.

like image 30
dognotdog Avatar answered Dec 26 '22 22:12

dognotdog