Last active
July 29, 2017 05:22
-
-
Save louisswarren/22c1919dff6611ada0965213df4e575e to your computer and use it in GitHub Desktop.
Generics in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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