Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active Jul 29, 2017
Embed
What would you like to do?
Generics in C
/* See http://stackoverflow.com/a/16523865 */
#include <stdio.h>
#include "sum.h"
define_sum(int);
define_sum(double);
int main(void)
{
double array1[] = {0.5, 1.5, 4.0};
int array2[] = {1,2,3,4};
printf("Double sum was %0.2G\n", sum(double)(array1, 3));
printf("Integer sum was %d\n", sum(int)(array2, 4));
return 0;
}
#define sum(T) sum_##T
#define define_sum(T) \
T sum_##T(T *values, size_t n) { \
T sum = 0; \
size_t i = 0; \
for (i = 0; i < n; ++i) { \
sum += values[i]; \
} \
return sum; \
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment