Created
June 9, 2019 03:52
-
-
Save sjkillen/5571d93455315bb81af491b223deaf39 to your computer and use it in GitHub Desktop.
Function overloading in C
This file contains hidden or 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
#include <stdio.h> | |
#include <stdlib.h> | |
enum discriminateFunc { | |
NO_RETURN, | |
INT_RETURN, | |
INT_RETURN_TAKE_INT, | |
}; | |
union funcUnion { | |
void (*no_return)(); | |
int (*int_return)(); | |
int (*int_return_take_int)(int); | |
}; | |
static void __overloaded(enum discriminateFunc d, union funcUnion f) { | |
switch (d) { | |
case NO_RETURN: | |
f.no_return(); | |
break; | |
case INT_RETURN: { | |
int ret = f.int_return(); | |
printf("Called func and it returned %d\n", ret); | |
break; | |
} | |
case INT_RETURN_TAKE_INT: { | |
int ret = f.int_return_take_int(42); | |
printf("Called func with 42 and it returned %d\n", ret); | |
break; | |
} | |
} | |
} | |
void A() { | |
printf("Called func with no args and no return\n"); | |
} | |
int B() { | |
printf("Called func with no args and returns 32\n"); | |
return 32; | |
} | |
int C(int arg) { | |
printf("Called func with int arg (got %d) and returns 14\n", arg); | |
return 14; | |
} | |
#define overloaded(d, x) __overloaded(d, (union funcUnion)x) | |
int main() { | |
overloaded(NO_RETURN, A); | |
overloaded(INT_RETURN, B); | |
overloaded(INT_RETURN_TAKE_INT, C); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment