How to use struct and union to hold different types in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

#define FLOAT_TYPE 1
#define CHAR_TYPE  2
#define INT_TYPE   3

struct var_type {
    int type_in_union;
    union {
        float unionfloat;
        char  unionchar;
        int   unionint;
    } var_type_union;
} var_type_struct;

void print_var_type(void) {

    switch (var_type_struct.type_in_union) {
        case FLOAT_TYPE:
            printf("%f\n", var_type_struct.var_type_union.unionfloat);
            break;
        case CHAR_TYPE:
            printf("%c\n", var_type_struct.var_type_union.unionchar);
            break;
        case INT_TYPE:
            printf("%d\n", var_type_struct.var_type_union.unionint);
            break;
        default:
            printf("Unknown type\n");
            break;
        }
}

main() {

    var_type_struct.type_in_union = FLOAT_TYPE;
    var_type_struct.var_type_union.unionfloat = 3.14;
    print_var_type();

    var_type_struct.type_in_union = CHAR_TYPE;
    var_type_struct.var_type_union.unionchar = 'z';
    print_var_type();

    var_type_struct.type_in_union = INT_TYPE;
    var_type_struct.var_type_union.unionint = 85903;
    print_var_type();


    return 0;
}



/*
run:

3.140000
z
85903

*/

 



answered Jun 9, 2024 by avibootz

Related questions

2 answers 165 views
1 answer 165 views
2 answers 314 views
1 answer 174 views
174 views asked Dec 27, 2020 by avibootz
1 answer 199 views
...