Undefined behavior on reading object using non-character type when last written using character type

后端 未结 2 2057
生来不讨喜
生来不讨喜 2020-12-09 09:13

Assuming unsigned int has no trap representations, do either or both of the statements marked (A) and (B) below provoke undefined behavior, why or why not, and

2条回答
  •  没有蜡笔的小新
    2020-12-09 10:04

    The authors of the Standard acknowledge in the rationale that it would be possible for an implementation to be conforming but useless. Because they expected that implementers would endeavor to make their implementations useful, they didn't think it necessary to mandate every behavior that might be needed to make an implementation suitable for any particular purpose.

    The Standard imposes no requirements on the behavior of code that accesses an aligned object of character-array type as some other type. That doesn't mean that they intended that implementations should do something other than treat the array as untyped storage in cases where code takes the address of the array once but never accesses it directly. The fundamental nature of aliasing is that it requires that an item be accessed in two different ways; if an object is only ever accessed one way, there is by definition no aliasing. Any quality implementation which is supposed to be suitable for low-level programming should behave in useful fashion in cases where a char[] is used only as untyped storage, whether the Standard requires it or not, and its hard to imagine any useful purpose that would be impeded by such treatment. The only purpose that would be served by having the Standard mandate such behavior would be to prevent compiler writers from treating the lack of a mandate as being--in and of itself--a reason not to process such code in the obvious useful fashion.

提交回复
热议问题