Can we use static_assert to detect padding in a struct?

邮差的信 提交于 2019-11-29 08:42:16

There may in theory be padding at the end of the struct after t, which your assert does not catch (which may or may not be intended). Your assumption is otherwise correct and this is perfectly fine use of offsetof and static_assert, to detect padding anywhere between member variables.

A better alternative might be:

static_assert( offsetof(struct quad, t) == sizeof(struct quad)-sizeof(int),

This also catches padding at the end of the struct. In addition, it makes the assertion more flexible in case the struct members are changed during code maintenance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!