float b = 1.0f;
int i = b;
int& j = (int&)i;
cout<<j<<endl;
o/p = 1
But for the following scenario
float b = 1.0f;
int i = b;
int& j = (int&)b;
cout<<j<<endl;
O/P = 1065353216
since both are having the same value it shall show the same result …Can anyone please let me know whats really happening when i am doing some change in line number 3 ?
Integer
1and floating-point1.0fmay be mathematically the same value, but in C++ they have different types, with different representations.Casting an lvalue to a reference is equivalent to
reinterpret_cast; it says “look at whatever is in this memory location, and interpret those bytes as anint“.In the first case, the memory contains an
int, so interpreting those bytes as anintgives expected value.In the second case, the memory contains a
float, so you see the bytes (or perhaps just some of them, or perhaps some extra ones too, ifsizeof(int) != sizeof(float)) that represent the floating-point number, reinterpreted as an integer.Your computer probably uses 32-bit
intand 32-bit IEEEfloatrepresentations. Thefloatvalue1.0fhas a sign bit of zero, an exponent of zero (represented by the 8-bit value 127, or 01111111 in binary), and a mantissa of 1 (represented by the 23-bit value zero), so the 32-bit pattern would look like:When reinterpreted as an integer, this gives the hex value
0x3f800000, which is 1065353216 in decimal.