I have 3 functions written in C.
int greatest_int(int* arr, int arr_size) {
int g_int = arr[0]; //g_int is short for greatest_integer
for (int i = 1; i < arr_size; i++)
if (arr[i] > g_int)
g_int = arr[i];
return g_int;
}
long greatest_long(long* arr, int arr_size) {
long g_long = arr[0];
for (int i = 1; i < arr_size; i++)
if (arr[i] > g_long)
g_long = arr[i];
return g_long;
}
double greatest_float(double* arr, int arr_size) {
double g_float = arr[0];
for (int i = 1; i < arr_size; i++)
if (arr[i] > g_float)
g_float = arr[i];
return g_float;
}
The three functions basically follow the same process. The only difference is that they operate on different types. I want to reduce this duplicated code, and make one generic function that works for any primitive types.
One idea that I thought of is to use function macros. For example, the below macro works for any primitive types.
#define MAX(a, b) ((a) > (b)) ? (a) : (b)
Here's the macro that I tried writing.
#define GREATEST(type, arr, size) {\
type g_value = arr[0];\
for (int i = 1; i < (size); i++)\
if (arr[i] > g_value)\
g_value = arr[i];\
return g_value;\
}
This macro does not represent any numeric value, it only expands to a bunch of statements.
How can I fix the macro so that it expands to the greatest value of the array? (Or is my macro approach flawed to begin with?)