共享第一个元素的结构联合是否存在未定义行为?
SDL_Event 是一个无符号 8 位类型和许多结构体的联合,其第一个元素是无符号 8 位类型。推荐的用法是访问联合体的 Uint8 元素来确定事件的类型,然后通过适合该类型的元素访问联合体。
这显然取决于联合中的所有类型都为类型标识符保留了相同的空间。我们能否确定是这种情况,还是这是未定义的行为?
编辑:使标题更具描述性。
SDL_Event is a union of an unsigned 8 bit type, and many structs whose first element is an unsigned 8 bit type. The reccomended usage is to access the Uint8 element of the union to determine what type the event is, and then access the union by the element appropriate to that type.
This obviously depends on all of the types in the union having the same space reserved for the type identifier. Can we be sure this is the case, or is this undefined behavior?
Edit: made the title more descriptive.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
结构体的第一个元素保证位于结构体开头的“偏移量 0”处。所以应该是安全的。
The first element of a struct is guaranteed to be at "offset 0" from the struct's beginning. So it should be safe.
我在C99标准中找到了它。
6.5.2.3.5:
所以看起来 SDL 实现已经接近保证正确的东西了。如果它使用仅包含 Uint8 的结构,则可以保证,但我认为裸 Uint8 是未定义的行为,极有可能按预期工作。
I found it in the C99 standard.
6.5.2.3.5:
So it looks like the SDL implementation is close to something guaranteed to be correct. If it were using a struct containing only a Uint8 then it would be guaranteed, but I think the naked Uint8 is undefined behavior that is extremely likely to work as expected.