共用体に先頭要素が共通している構造体が含まれている場合

K&R本 付録A8.3

共用体の利用を簡単にするのには、一つ特別な方法が用意されている。ある共用体に、先頭のメンバー並びが共通しているいくつかの構造体が含まれていて、しかも共用体がいまそれらの構造体の一つを保持しているときには、含まれている任意の構造体の共通先頭部分を参照することが許されている。例えば、次に示すのは文法的に正しいプログラムである。

union {
    struct {
        int type;
    } n;
    struct {
        int type;
        int intnode;
    } ni;
    struct {
        int type;
        float floatnode;
    } nf;
} u;
...
u.nf.type = FLOAT;
u.nf.floatnode = 3.14;
...
if ( u.n.type == FLOAT )
    ... sin(u.nf.floatnode) ...

なるほど。共用体に定義されているそれぞれの構造体の先頭要素が共通してるならこういうやり方もありという話か。

でのこのケースならstructの中にunionした方が良いような気はする。

struct {
    int type;
    union {
        int intnode;
        float floatnode;
    } u;
} s;
...
s.type = FLOAT;
s.u.floatnode = 3.14f;
...
if ( s.type = FLOAT )
    ... sin(s.u.floatnode) ...