Passing different types to the same function

Viewed 52

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);
}
1 Answers

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.

Related