Created
February 17, 2013 08:51
-
-
Save danhper/4970701 to your computer and use it in GitHub Desktop.
Example usage of union
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
#include <stdio.h> | |
#include <stdlib.h> | |
typedef union { | |
int i; | |
double d; | |
} int_or_double; | |
typedef enum { | |
INT, | |
DOUBLE | |
} number_type; | |
typedef struct { | |
number_type type; | |
int_or_double n; | |
} number; | |
number add(const number* a, const number* b) | |
{ | |
number ret; | |
if(a->type == INT && b->type == INT) { | |
ret.type = INT; | |
ret.n.i = a->n.i + b->n.i; | |
} else { | |
double x = a->type == INT ? a->n.i : a->n.d; | |
double y = b->type == INT ? b->n.i : b->n.d; | |
ret.type = DOUBLE; | |
ret.n.d = x + y; | |
} | |
return ret; | |
} | |
void print_number(const number* num) | |
{ | |
if(num->type == INT) { | |
printf("%d\n", num->n.i); | |
} else { | |
printf("%f\n", num->n.d); | |
} | |
} | |
number make_int(int i) | |
{ | |
int_or_double u; | |
u.i = i; | |
number num = {INT, u}; | |
return num; | |
} | |
number make_double(double d) | |
{ | |
int_or_double u; | |
u.d = d; | |
number num = {DOUBLE, u}; | |
return num; | |
} | |
int main(void) | |
{ | |
number a = make_int(8); | |
number b = make_int(6); | |
number c = make_double(4.5); | |
number res1 = add(&a, &b); | |
number res2 = add(&a, &c); | |
print_number(&res1); | |
print_number(&res2); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment