Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

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 133 views
1 answer 135 views
2 answers 272 views
1 answer 147 views
147 views asked Dec 27, 2020 by avibootz
1 answer 175 views
...