0

I have function sum( data) and I need to call this function inside multi functions and in each time pass to sum(data) different type of data. I do not know how to define the parameter of the function sum(data) to accept different types. For example:

void sum( "what is the type here" data){
// some processing 

}
void x(){
 // some processing 
  //float data
   sum(data);
}
void y(){
  // some processing 
  //int data
   sum(data);
}
void z(){
 // some processing 
 //double data
  sum(data);
}
lena
  • 730
  • 2
  • 11
  • 23
  • C does not have generics. You must either put all your data into the same type or write multiple functions, one for each type. [You can simulate generics using a macro-include trick, though](https://stackoverflow.com/a/16522430/2706707). – Dúthomhas Apr 09 '22 at 22:46
  • 2
    You can't do that in C. You can use `_Generic` (from C11) to have three distinctly named functions (e.g. `void sum_f(float *data);`, `void sum_i(int *data)`, `void sum_d(double *d)`) mapped so that you write `sum(data)` but the distinct functions are called. In C++, you could probably use templates, but you'd end up with three different functions for the three different types, but you'd have function overloading to select the correct versions. You could have the overloading even without using templates. – Jonathan Leffler Apr 09 '22 at 22:47
  • This question may be somewhat related: [Is it possible for a c function to accept both double and long double arguments?](https://stackoverflow.com/q/71789746/12149471) – Andreas Wenzel Apr 09 '22 at 22:57
  • Perhaps you could also pass a `void *` and some other information about the actual type and call the right function. – alex01011 Apr 09 '22 at 23:32

1 Answers1

0

As I noted in the comments, you can't do that in C. You can use _Generic from C11 to have three distinctly named functions such as:

  • void sum_f(float data);
  • void sum_i(int data);
  • void sum_d(double data);

mapped so that you write sum(data) but the distinct functions are called. Obviously, you have to implement the three functions and make sure they are declared. Then you could use:

#define sum(x) _Generic((x), int: sum_i, float: sum_f, double sum_d)

void x(){
    // some processing 
    float data = …;
    sum(data);
}

void y(void){
    // some processing 
    int data = …;
    sum(data);
}
void z(void){
   // some processing 
   double data = …;
   sum(data);
}

In C++, you could probably use templates, but you'd end up with three different functions for the three different types, and you'd have function overloading to select the correct versions. You could have the overloading even without using templates.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278