How to use union inside struct to represent different types in C

2 Answers

0 votes
#include <stdio.h>

#define INT 0
#define FLOAT 1
#define CHAR_P 2

union u {
    int i;
    float f;
    char* s;
};

struct types {
    char what_type;
    union u val;
} v;

void function(struct types *p) {
    switch (p->what_type) {
        case INT:
            printf("%d\n", p->val.i);
            break;
        case FLOAT:
            printf("%f\n", p->val.f);
            break;
        case CHAR_P:
            printf("%s\n", p->val.s);
            break;
    }
}

int main()
{
    v.val.i = 7483;
    v.what_type = INT;
    function(&v);

    v.val.f = 3.14f;
    v.what_type = FLOAT;
    function(&v);

    v.val.s = "C Programming";
    v.what_type = CHAR_P;
    function(&v);


    return 0;
}




/*
run:

7483
3.140000
C Programming

*/



 



answered May 23, 2023 by avibootz
0 votes
#include <stdio.h>

#define INT 0
#define FLOAT 1
#define CHAR_P 2

typedef union {
    int i;
    float f;
    char* s;
} u;

typedef struct {
    char what_type;
    u val;
} types;

void function(types *p) {
    switch (p->what_type) {
        case INT:
            printf("%d\n", p->val.i);
            break;
        case FLOAT:
            printf("%f\n", p->val.f);
            break;
        case CHAR_P:
            printf("%s\n", p->val.s);
            break;
    }
}

int main()
{
    types v;

    v.val.i = 7483;
    v.what_type = INT;
    function(&v);

    v.val.f = 3.14f;
    v.what_type = FLOAT;
    function(&v);

    v.val.s = "C Programming";
    v.what_type = CHAR_P;
    function(&v);


    return 0;
}




/*
run:

7483
3.140000
C Programming

*/



 



answered May 23, 2023 by avibootz

Related questions

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