开发者

Is a union of structs sharing a first element undefined behavior?

开发者 https://www.devze.com 2023-02-03 17:00 出处:网络
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

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 h开发者_JS百科aving 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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消