4 ms·
"There's no "bitcast" operator that changes the type of a value without affecting the value." Technically, you are supposed to use unions for that, though it's
by jeffdavis 7y ago
"There's no "bitcast" operator that changes the type of a value without affecting the value."
Technically, you are supposed to use unions for that, though it's a pain. The PostgreSQL codebase is compile with -fno-strict-aliasing so that a simple cast will get the job done, but obviously that's technically out of spec.
- jcranmer 7y agoActually, 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.
- pwdisswordfish2 7y agoOr better, memcpy.
- makapuf 7y agoWhich in this case may or may not copy memory. You're only able to express changing the meaning of some specific bytes by moving them which is the contrary of what you meant. Sure you're not moving things because normally the compiler will (and does) optimize, but you must say that you need the bytes to be copied.