-
-
Save barosl/e0af4a92b2b8cabd05a7 to your computer and use it in GitHub Desktop.
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int addi(int a, int b) { | |
return a + b; | |
} | |
char *adds(char *a, char *b) { | |
char *res = malloc(strlen(a) + strlen(b) + 1); | |
strcpy(res, a); | |
strcat(res, b); | |
return res; | |
} | |
#define add(a, b) _Generic(a, int: addi, char*: adds)(a, b) | |
int main(void) { | |
int a = 1, b = 2; | |
printf("%d\n", add(a, b)); // 3 | |
char *c = "hello ", *d = "world"; | |
printf("%s\n", add(c, d)); // hello world | |
return 0; | |
} |
Is there a way to do stricter type checking on more than one argument? As I read this, it is only checking the type of the first argument?
-
Type checking only on one argument
-
main leaks memory
@jasiek: The Arduino IDE uses C++, so function overloading works just fine. (So do templates, but you have to define them in a .h file rather than the default extension-less file.)
@KLuka
It's not good practice to not free something you've malloc'd.
Still not supported by Intel C compiler though.
@dubslow Yes, main leaks memory. I realize now that github has its own "grammar police" since that was not the point of this gist.
@Fusion I'd say it's not github, but C community, as memory leaks is something to avoid even in examples that are this simple.
DAE notice the memory leak???????????????
OMG did you guys see the memory leak?!!
'a' gets evaluated twice
There is a memory leak. You allocate with malloc but you never free the allocated memory. You should fix that.
Who says C can't be high-level and beautiful? <3
Without C11: