How to get access to a union member without naming him?

I have a code that is very similar to the following

struct T {
    union {
        unsigned int x;
        struct {
            unsigned short xhigh;
            unsigned short xlow;
        };
    } x;
    /* ...repeated a handful of times for different variables in T... */
};

This does exactly what you expect: it allows me to declare a type variable struct Tand access t.x.xeither t.x.xhighor or t.x.xlow. So far so good.

Nevertheless, I would very much like if I could only dot.x in the general case, to gain access to the value of the union as a quantity unsigned int, but to retain the ability to access high and low order sections independently, without resorting to masking and bit shifting, and not causing undefined behavior.

Is this possible in C?

If possible, what is the C syntax for the declaration?

naiive- t.x t.x.x, ( printf()):

cc -ansi -o test -Wall test.c
test.c: In functionmy_function’:
test.c:13:2: warning: format ‘%Xexpects argument of typeunsigned int’, but argument 2 has typeconst union <anonymous>’ [-Wformat]

-std=c11 -ansi .

+4
1

- , ( C11, ).

, struct union, union , . :

struct T {
    union {
        unsigned int x;
        struct {
            unsigned short xhigh;
            unsigned short xlow;
        };
    }; /* <-- no name here */

    /* ...repeated a handful of times for different variables in T... */
};

, , , .


: , , "", unsigned short unsigned int, . , . , .

+7

Source: https://habr.com/ru/post/1677318/


All Articles