共享第一个元素的结构联合是否存在未定义行为?

发布于 2024-10-11 12:30:14 字数 261 浏览 7 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乱了心跳 2024-10-18 12:30:15

结构体的第一个元素保证位于结构体开头的“偏移量 0”处。所以应该是安全的。

The first element of a struct is guaranteed to be at "offset 0" from the struct's beginning. So it should be safe.

已下线请稍等 2024-10-18 12:30:15

我在C99标准中找到了它。

6.5.2.3.5:

为了简化联合的使用,做出了一项特殊保证:如果联合包含
共享共同初始序列的几个结构(见下文),并且如果并集
对象当前包含这些结构之一,允许检查公共结构
它们中任何一个的初始部分,只要声明了联合的完整类型
可见的。如果相应的成员具有,则两个结构共享共同的初始序列
一个或多个序列的兼容类型(对于位字段,具有相同的宽度)
初始成员。

所以看起来 SDL 实现已经接近保证正确的东西了。如果它使用仅包含 Uint8 的结构,则可以保证,但我认为裸 Uint8 是未定义的行为,极有可能按预期工作。

I found it in the 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 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 complete type of the union is
visible. Two structures share a common initial sequence if corresponding members have
compatible types (and, for bit-fields, the same widths) for a sequence of one or more
initial members.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文