7 ms·
Do I understand you right that for (int i=0; i<4; i++) buf[i] = ((char*)&my_float)[i]; is not undefined behavior? But that for (int i=0; i<4; i++)
by yvdriess 3y ago
Do I understand you right that
for (int i=0; i<4; i++)
buf[i] = ((char*)&my_float)[i];
is not undefined behavior? But that
for (int i=0; i<4; i++)
buf[i] = ((char*)(int32_t*)&my_float)[i];
is undefined?
- pif 3y agoI'm not sure 100%, but your second example does not imply UB. UB is caused by the act of accessing an object via a pointer of the wrong type, but just casting a pointer as you do should not be a problem. On the other side, this would incur UB: int32_t my_int = *((int32_t*)&my_float);