Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access union member in c

Tags:

c

unions

I have a question about union in c language

for example:

typedef struct {
    int a;
     float c;
}Type1;


typedef struct {
    int b;
     char d;
}Type2;

union Select {
    Type1 type1;
    Type2 type2;
};


void main() {
    Select* select;
    //can we access type1 first and then access type2 immediately? like this way:
    select->type1.a;
    select->type2.b;

//after access type1, and then access type2 immediately, can we get the value b of type2? //I modify the first post a little bit, because it is meanless at the beginning.

}


1 Answers

This is guaranteed to work by ISO/IEC 9899:1999 (see the draft here), 6.5.2.3 5:

One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the complete type of the union is visible. Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.

like image 172
undur_gongor Avatar answered Oct 29 '25 08:10

undur_gongor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!