Home > Back-end >  C99 write data directly into union type
C99 write data directly into union type

Time:01-31

I have a union type declared as follows:

typedef union Data{
    int i;
    char c;
    double d;
    float f;
} data;

I know fields are overwritten by new values. I would like to know if there is any way to do the following instead of needing to manually access each field depending on the type of data i want to store:

    data* c;
    *c = 3; //instead of c.i = 3; c.i should be 3
    *c = 'a' //instead of c.c = 'a'; c.c should be 'a', c.i should no longer be 3;

i tried doing as written above, but i get an error saying: Assigning to 'data' (aka 'union Data') from incompatible type 'int'.

Is there any way to do this?

CodePudding user response:

No. It's not possible. If you want type switching use _Generic but 'a' is an integer character constant (i.e. type is int) so you will only find partial success with sample input provided:

#include <stdio.h>

typedef union {
    char c;
    double d;
    float f;
    int i;
} data;

#define set(d, v) _Generic((v),\
    char: setc,\
    double: setd,\
    float: setf,\
    int: seti\
)((d), (v))

void setc(data d, int v) {
    d.c = v;
    printf("c = %c\n", d.c);
}

void setd(data d, double v) {
    d.d = v;
    printf("d = %lf\n", d.d);
}

void seti(data d, int v) {
    d.i = v;
    printf("i = %d\n", d.i);
}

void setf(data d, float f) {
    d.f = f;
    printf("f = %f\n", d.f);
}

int main() {
    data d = { 0 };
    set(d, 'a'); // seti()
    char c = 'c'; set(d, c); // or set(d, (char) 'c');
    set(d, 3.14);
    set(d, 1.2f);
    set(d, 3);
}

and the resulting output:

i = 97
c = c
d = 3.140000
f = 1.200000
i = 3
  •  Tags:  
  • cc99
  • Related