问题
I want to do something like this:
union U {
int i;
double d;
};
void foo (double *d) { *d = 3.4; }
int main ()
{
union U u;
foo (&(u.d));
}
gcc
does not complain (with -Wall -Wextra
) and it works as expected, but I would like to make sure it is actually legal (according to the standard).
回答1:
Why shouldn't it be legal? Actually, it's even guaranteed that the addresses of every member is equal to the address of whole union:
A pointer to a union object, suitably converted, points to each of its members [...] and vice versa.
(C11, §6.7.2.1 16)
(which implies that you can take a pointer to union members)
回答2:
Yes this is legal, and there would be no reason for it not to be. Simple as that.
回答3:
C99:
6.5.3.2
Address and indirection operators
Constraints
- The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier
[...]
object region of data storage in the execution environment, the contents of which can represent values
So, yes, a union is an object and therefore may be an operand of & as long as it meets the other requirements.
来源:https://stackoverflow.com/questions/15444588/is-it-legal-to-take-the-address-of-an-union-member-in-c