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