Let’s say I have the following bit of code, which tries to ‘downcast’ a double value into a uint8_t:
uint8_t downcast(uint8_t *down1, uint8_t *down2)
{
//the usual nullptr checks
double fval = 100.0; //fits the uint8_t domain range
*down1 = (uint8_t)fval; //should work...
fval = 1000.0; //does not fit uint8_t domain range
*down2 = (uint8_t)fval; //will this work??
}
I’ve seen a few posts that suggest doing this sort of "quantization-cast", but I’m not sure this is correct. I seem to recall reading that a double var whose value exceeds the output domain, will lead to undefined behavior from the cast (either C or static_cast<uint8_t>(fval)).
Thoughts?
>Solution :
The behaviour of the second cast is undefined.
C17 §6.3.1.4 ¶1 When a finite value of real floating type is converted to an integer type other than
_Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.