Answer the question
In order to leave comments, you need to log in
How to explain this piece of code?
I'm very bad at c++
There is a code snippet:
unsigned long long num = 0xC068C0C000000000;
cout << *(double *) #
unsigned long long num = 0xC068C0C000000000;
cout << (double) num;
Answer the question
In order to leave comments, you need to log in
This code demonstrates a typical type punning error (type punning [ ? ]), leading to inevitable UB [ ? ] according to the standard.
num in this case is a hexadecimal number, it is converted to a double decimal number on output.
If a program attempts to access the stored value of an object through a glvalue whose type is not similar to one of the following types the behavior is undefined:
(11.1) -- the dynamic type of the object,
(11.2) -- a type that is the signed or unsigned type corresponding to the dynamic type of the object, or
(11.3) -- a char, unsigned char, or std::byte type.
unsigned long long
type double
does not have any of the properties required by the standard. Hence the direct conclusion that this code contributes UB. char
, unsigned char
or std::byte
for C ++ 17. union
. This really should not be done, even if all modern translators understand such constructions in the way the writer suspects.Why does the following code fragment work incorrectly, for example:
unsigned long long
to type double
. In this case, it is a standard type conversion that is performed, and not a substitution in order to interpret the memory representation in num
a different way. 0xC068C0C000000000
for type unsigned long long
means 13864543383726325760
, when this value is converted to type , the double
value will be converted to 1.3864543383726326e+19
. In this form, it will be displayed. unsigned long long num = 0xC068C0C000000000;
double representation = {};
memcpy( &representation, &num, sizeof( num ) );
cout << representation;
memcpy
here. This code fully complies with the standard and is expected to be optimized by the compiler to the desired result.It is not clear to me how such a construction works, i.e. why pass a reference to the num variable?
num stores the binary representation of double in IEEE 754 format . The code allows you to forget that this is an int, and interpret this binary data as a double.
Your version will simply translate the unsigned integer num (13864543383726325760) into double (1.3864543383726326e+19)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question