Reputation: 4767
Let's say I have the following tagged union:
typedef struct Form {
FormType type;
union {
TaxForm tax;
BusinessForm bus;
} u;
} Form;
To access the main/sub object I have to do:
form->u.bus
Is there a way to either do:
form->u
Or:
form->bus
That is, to be able to access union object directly without going through its declarator (since by definition, the union will only have one item set).
Upvotes: 1
Views: 68
Reputation: 141638
You can only do this by omitting the u
from the original definition:
typedef struct Form {
FormType type;
union {
TaxForm tax;
BusinessForm bus;
}; // <--- no u
} Form;
Then you can use form->bus
and so on, where form
is a pointer to Form
.
This is called "anonymous unions" and was added in the C11 standard revision , so you will need to invoke your compiler in C11 or later mode, or hope that it supported this as an extension in older modes.
Upvotes: 2