is it legal to take the address of an union member in C?

丶灬走出姿态 提交于 2019-12-24 00:19:50

问题


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

  1. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!