Function for total sum in c

Is it possible to write a generic sum function in C?

I am trying to write one sum function that handles any numeric type.

double sum(void* myArrayVoidPtr, size_t arrayLength, int arrayType){
    int i;
    double result = 0;

    //The goal is to make this next line depend on arrayType
    //e.g. if(arrayType == UINT16)
    unsigned short* myArrayTypePtr = (unsigned short*) myArrayVoidPtr;

    for(i = 0; i < arrayLength; i++){
        result += *myArrayTypePtr;
        myArrayTypePtr++;
    }
    return result;
}

      

+3


source to share


1 answer


There is no way to create a generic function in C. Unlike C ++, you don't have templates . Templates allow you to create multiple versions of the same function that differ type

(ie - int

, float

or any class

) that they accept. This means that the function is compiled more than once.

C has no templates, but you can write a macro for it. It is basically the equivalent of C ++ templates, less powerful. This will be "inlined", although not a real function.

#define SUM(arr, len, sum) do { int i; for(i = 0; i < len; ++i) sum += arr[i]; } while(0);

int main(void) {
    int i_arr[] = {1,2,3};
    double d_arr[] = {1.5, 2.5, 3.5};
    int sum = 0;
    double d_sum = 0;
    SUM(i_arr, 3, sum)
    SUM(d_arr, 3, d_sum);
    printf("%d, %f\n", sum, d_sum);
    return 0;

}

      



Output:

6, 7.500000

      

+3


source







All Articles