Type punning and Unions in C

后端 未结 2 1840
有刺的猬
有刺的猬 2020-11-30 12:23

I\'m currently working on a project to build a small compiler just for the heck of it.

I\'ve decided to take the approach of building an extremely simple virtual mac

2条回答
  •  情歌与酒
    2020-11-30 13:25

    As long as you only access the member (int or float) which was most recently stored, there's no problem and no real implementation dependency. It's perfectly safe and well-defined to store a value in a union member and then read that same member.

    (Note that there's no guarantee that int and float are the same size, though they are on every system I've seen.)

    If you store a value in one member and then read the other, that's type punning. Quoting a footnote in the latest C11 draft:

    If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called "type punning"). This might be a trap representation.

提交回复
热议问题