5 ms·
IMO it’s pretty iffy and you should steer clear of it, since the rules around it seem to be murky. I think the actual rule is that it’s illegal in C++, and vali
by saagarjha 8y ago
IMO it’s pretty iffy and you should steer clear of it, since the rules around it seem to be murky. I think the actual rule is that it’s illegal in C++, and valid in C99 and C11 but only because it was included in a footer note as an afterthought in the standard.
- comex 8y agoFrom a standards perspective that’s pretty much right AFAIK. From a practical perspective, it’s also explicitly endorsed in the GCC manual, so I don’t think there’s much risk of popular compilers breaking it in the foreseeable future: > The practice of reading from a different union member than the one most recently written to (called “type-punning”) is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type. So, the code above works as expected. https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
- jancsika 8y agoSo what is the well-defined and performant way to fetch the exponent and mantissa of a double in standard C?
- saagarjha 8y agoUse frexp from <math.h>.
- jancsika 8y agoThe implementation for frexp uses type-punning. Also, it adds a denormal and inf check which I don't need in this particular hot loop.
- saagarjha 8y agoDoes it? On my computer it's a builtin (__builtin_frexp). But even if it did use type-punning, that doesn't make it legal for your program to do it. I don't believe there's any requirements on the C standard library to follow the standard themselves. To answer the second part of your response, the correct way to do this yourself would be to memcpy the double and then inspect the result directly. Any compiler worth its salt will end up generating the assembly code you want (namely, no call to memcpy, just a couple of arithmetic shifts and masks).
- jancsika 8y ago> To answer the second part of your response, the correct way to do this yourself would be to memcpy the double and then inspect the result directly. Any compiler worth its salt will end up generating the assembly code you want (namely, no call to memcpy, just a couple of arithmetic shifts and masks). What does a compiler "worth its salt" do with the memcpy at "-O0"?
- saagarjha 8y agoSee for yourself: https://godbolt.org/z/nsg9nt https://godbolt.org/z/nsg9nt