#include <stdio.h>
typedef struct {
int i_nt;
} A;
typedef struct {
double d_ouble;
} B;
typedef struct {
char s_tring[32];
} C;
typedef enum {
TypeAint,
TypeBdouble,
TypeCstring,
} type;
typedef struct {
type type;
union { A* i_nt; B* d_ouble; C* s_tring; } typesunion;
} AllTypes;
void foreach(AllTypes* alltypes, void (*fnptr)(TypedPointer)) {
while (alltypes->typesunion.i_nt) {
fnptr(*alltypes);
++alltypes;
}
}
void print_value(AllTypes at) {
switch (at.type) {
case TypeAint: printf("A int: %d\n", at.typesunion.i_nt->i_nt); break;
case TypeBdouble: printf("B double: %f\n", at.typesunion.d_ouble->d_ouble); break;
case TypeCstring: printf("C string: %s\n", at.typesunion.s_tring->s_tring); break;
}
}
int main()
{
A a = { .i_nt = 96 };
B b = { .d_ouble = 3.14 };
C c = { .s_tring = "C Programing" };
AllTypes arrOfTypes[] = { // array with different data types
{.type = TypeAint, .typesunion.i_nt = &a },
{.type = TypeBdouble, .typesunion.d_ouble = &b },
{.type = TypeCstring, .typesunion.s_tring = &c },
{.type = 0, .typesunion.i_nt = 0} }; // end foreach while loop
foreach(arrOfTypes, print_value);
return 0;
}
/*
run:
A int: 96
B double: 3.140000
C string: C Programing
*/