Exception to strict aliasing rule in C from 6.5.2.3 Structure and union members

前端 未结 2 1654
[愿得一人]
[愿得一人] 2021-01-05 16:34

Quote from C99 standard:

6.5.2.3

5 One special guarantee is made in order to simplify the use of unions: if a union contains several structures th

2条回答
  •  清酒与你
    2021-01-05 17:02

    The set of circumstances in which a compiler recognizes that an access to an aggregate member is an access to the aggregate itself is purely a Quality of Implementation issue, and the Standard makes no effort to recognize any cases where use of a non-character lvalue of the form aggregate.member or pointerToAggregate->member would not violate 6.5p7. A compiler which couldn't handle at least some cases as defined would be of such low quality as to be pretty useless, but the Standard makes no effort to forbid conforming-but-useless implementations.

    If a common initial sequence member has a character type, then 6.5p7 would define the behavior of accessing it, regardless of whether it is a member of a common initial sequence of a union whose complete declaration is visible. If it doesn't have a character type, then access would only be defined under 6.5p7 if performed through an lvalue of character type or memcpy/memmove, or in cases where the destination has heap duration and the ultimate type used for a read matches the type used for a write.

    There are a number of indications a quality compiler should recognize that would suggest a pointer to one structure type might be used to access a CIS member of another. A compiler that is unable to recognize any of the other indications might benefit from treating the existence of a complete union declaration containing both types as such an indication. Doing so might needlessly block some otherwise-useful optimizations, but would still allow more optimizations than disabling type-based aliasing analysis altogether.

提交回复
热议问题