I am bit confused about implicit type conversion. Given the following program
float x = 4.23423451;
double y = 4.23423451;
float z = 101.9876;
float res1 = x * z;
float res2 = y * z;
std::cout << "res1 & res2 " << res1 << " & " << res2 << std::endl;
std::cout << "equality " << (res1 == res2) << std::endl;
The output was
res1 & res2 431.839 & 431.839
equality 1
My question is “Will the equality be always true for any value of x, y & z (x = y) and also for any compiler?”
In
res2 = y * z;
Will the variable “y” be type-casted to float or variable “z” be type-casted to double?
See my comments.
This is reflected by §5¶9 Expressions [expr] of the C++11 standard.
This, however, does not sure that the equality will hold.
See §5.17¶3 Assignment and compound assignment operators [expr.ass].
§4 Standard conversions [conv] states as follows:
As elaborated in §4.6 Floating point promotion [conv.fpprom],
… and §4.8 Floating point conversions [conv.double],
The problem here is that we have multiple cases where our conversion is not promotion, but rather narrowing to a potentially lower-precision type (
doubletofloat).Essentially, any time you convert
doubletofloat, you may potentially lose precision.