I know, I saw it already but I couldn't find any good explanation why is this undefined behaviour:
#include <stdio.h>
#include <stdint.h>
//Common union for both types
union float_int {
float f;
uint32_t i;
};
int main(void) {
union float_int fi;
//This should be problematic
uint32_t* i_ptr = (uint32_t *)&fi.f;
fi.f = 10.0f;
printf("%f : %u\r\n", fi.f, fi.i); //Prints: 10.000000 : 1092616192 which is OK
printf("%u\r\n", *i_ptr); //Prints: 1092616192 which is also OK
return 0;
}
If we check memory representation, both are 4-bytes
long so there is no memory overflow in pointing or similar.
How is this undefined behaviour?
int main() {
union float_int fi;
void* v_ptr = &fi.f;
uint32_t* i_ptr = (uint32_t *)v_ptr;
}
Is this code still undefined behaviour? I want to read float
number as unsigned integer 32-bits
.
Why is using memcpy
the only available way of doing it?