Last active
December 16, 2015 04:09
-
-
Save jonathanmarvens/5375010 to your computer and use it in GitHub Desktop.
Today, a friend of mine asked me to show him an example of how one can create a function in C that accepts an argument of different specified types. This example is what I came up with in about 3 minutes while on the phone with him (so it most likely can be better). Needless to say, I used a `union` in order to provide this functionality. Due to…
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 <string.h> | |
#define INT_OR_STR_INT 1 | |
#define INT_OR_STR_STR 2 | |
typedef struct | |
{ | |
unsigned int type; | |
union | |
{ | |
unsigned int integer; | |
// I think I can safely assume that no one is older than 999. | |
char string[ 4 ]; | |
} value; | |
} int_or_str; | |
void print_age( int_or_str age ); | |
int main() | |
{ | |
int_or_str age_1; | |
int_or_str age_2; | |
age_1.type = INT_OR_STR_INT; | |
age_1.value.integer = 18; | |
print_age( age_1 ); | |
age_2.type = INT_OR_STR_STR; | |
strcpy( age_2.value.string, "18" ); | |
print_age( age_2 ); | |
return 0; | |
} | |
void print_age( int_or_str age ) | |
{ | |
switch ( age.type ) | |
{ | |
case INT_OR_STR_INT: | |
printf( "Age: %u.\n", age.value.integer ); | |
break; | |
case INT_OR_STR_STR: | |
printf( "Age: %s.\n", age.value.string ); | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment