Reputation: 4592
I have the function:
void print_sum(int list[], int length) {
float sum = 0.0;
int i;
for (i = 0; i < length; i++) {
sum += (float) list[i];
}
printf("Sum: %0.2f\n", sum);
}
I want, in the same function, can receive a array of int
or a array of float
, for example. How I can make it?
Upvotes: 1
Views: 35
Reputation: 1742
In C++, this could be done with a template. But in C, you can accomplish something like this with macros. One way is to replace the function with a macro:
#define PRINT_SUM(list,type,format,length) do{ \
type sum = 0; \
int i; \
for (i = 0; i < length; i++) { \
sum += (type) list[i]; \
} \
printf("Sum: " format "\n", sum); \
}while(0)
To use this, write something like PRINT_SUM(a,float,"%0.2f",3);
.
The other way is to define a macro that defines a function which receive a list of a given type:
#define DEFINE_PRINT_SUM(name,type,format) void name(type list[], int length) { \
type sum = 0.0; \
int i; \
for (i = 0; i < length; i++) { \
sum += (type) list[i]; \
} \
printf("Sum: "format"\n", sum); \
}
Then you can define a float version of print_sum
with DEFINE_PRINT_SUM(print_sum_float,float,"%0.2f")
.
Upvotes: 3