union of structs sharing same first members

泪湿孤枕 提交于 2019-11-29 04:12:58
Mints97

After some research, I think I have a qualified answer for this question.

The citation given was from the C89 standard. C99 and C11 have it rephrased like this:

One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible.

The last part can be interpreted, IMHO, in a variety of ways. However, the commitee left it as it is. According to them, it means that the inspection of the "common initial part" of the structures can be done only using an object of the union type that has been declared to contain them. That is very well demonstrated in this question.

What about C89, which seems to allow what I was trying to do? Well, in a C89-conforming compiler, yes, this should work. However, it might not really be needed: I don't know of a single strictly-C89-conforming compiler that supports strict aliasing, so, with them, it is easier to simply cast the structs with the common initial sequence to each other's types and try not to give them different packing settings. The result should be the same.

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