Created
March 14, 2020 01:43
-
-
Save strager/850c99b8c5fa2e1616751367a8044161 to your computer and use it in GitHub Desktop.
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> | |
union my_result_data { | |
int integer; | |
float floating; | |
}; | |
enum my_result_kind { | |
MY_RESULT_INTEGER, | |
MY_RESULT_FLOATING, | |
}; | |
struct my_result { | |
enum my_result_kind kind; | |
union my_result_data data; | |
}; | |
struct my_result add(int a, int b) | |
{ | |
puts("add"); | |
return (struct my_result){ | |
.kind = MY_RESULT_INTEGER, | |
.data = (union my_result_data){.integer = a+b}, | |
}; | |
} | |
struct my_result subtract(int a, int b) | |
{ | |
puts("subtract"); | |
return (struct my_result){ | |
.kind = MY_RESULT_INTEGER, | |
.data = (union my_result_data){.integer = a-b}, | |
}; | |
} | |
struct my_result funny(int a, int b) | |
{ | |
puts("funny"); | |
return (struct my_result){ | |
.kind = MY_RESULT_FLOATING, | |
.data = (union my_result_data){.floating = 1.0/(a*b)}, | |
}; | |
struct my_result r = { | |
.kind = MY_RESULT_FLOATING, | |
.data = (union my_result_data){.floating = 1.0/(a*b)}, | |
}; | |
struct my_result r; | |
r.kind = MY_RESULT_FLOATING; | |
r.data = (union my_result_data){.floating = 1.0/(a*b)}; | |
} | |
int result; | |
int main() | |
{ | |
// Now declaring the array of function pointers | |
struct my_result (*function_pointer[])(int, int) = {&add, &subtract, &funny}; | |
unsigned int choice = 0; int a=15, b=6; | |
scanf(">%ud", &choice); | |
if(choice>2) return 0; | |
struct my_result result = (*function_pointer[choice])(a, b); | |
switch (result.kind) { | |
case MY_RESULT_INTEGER: | |
printf("result was an integer: %d\n", result.data.integer); | |
break; | |
case MY_RESULT_FLOATING: | |
printf("result was a floating: %f\n", result.data.floating); | |
break; | |
default: | |
printf("I don't know what result was ...\n"); | |
break; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment