3 ms·
Actually, the guideline I've heard is that memcpy should be used, since memcpy has the magic property of copying the bytes without affecting the destination typ
by jcranmer 7y ago
Actually, the guideline I've heard is that memcpy should be used, since memcpy has the magic property of copying the bytes without affecting the destination type. Unions are only legal in C99 and newer (although C99 erroneously includes this in its list of undefined behavior--this was fixed in C11); C89 and any version of C++ don't permit this behavior.
- aidenn0 7y agoI keep hearing this rumor, but C99 did not erroneously include unions-as-type-punning in a list of undefined behavior. The normative language is unclear, but clarifications were added1][2]. 1: http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_257.htm http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_257.htm 2: http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_283.htm http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_283.htm
- quietbritishjim 7y agoThe parent comment seems to be saying that C99 does allow type punning with a union, with an explicit clarification as you say. In C89 it was ambiguous and in C++ it is explicitly disallowed (you are supposed to use memcpy).
- quietbritishjim 7y agoSorry, I misread the parent comment. Now it's too late to delete mine, please ignore.