Reputation: 1565
I have a union that is an overlay of an array on three floats:
union {
float currents[3];
struct {
float run;
float standby;
float sleep;
};
} MyCurrents;
run
can be accessed either by MyCurrents.run
or MyCurrents.currents[0]
.
Is there a way to have the currents
array anonymous, such that I can access run
by simply using MyCurrents[0]
? Having the .
accessor seems a bit redundant in this use case.
I realise I can use ((float*)&MyCurrents)[0]
but that's horrible and I'm not sure it's actually a reliable method to use.
Upvotes: 1
Views: 101
Reputation: 222526
Per the C standard, members that are structures or unions may be anonymous. This works because the members within them are not anonymous, so every subobject within the enclosing structure or union has a name. Anonymous members of other types are not supported (except that bit fields used for padding may be anonymous, but they are also not normally accessible).
(The C grammar allows you to include declarations without names (C 2018 6.7.2.1 1: The struct-declarator-list is optional in a struct-declaration), but they do not create members, and there would be no way of referring to them. And declaring a member without a name requires omitting the entire declarator of the grammar, which includes (per 6.7. 1) *
for pointers, [
and ]
for arrays, and (
and )
for functions. So the grammar would permit you to declare struct { float; float f; } foo;
but not struct { float [3]; float f; } foo;
.)
Upvotes: 3