Why is the following code frowned upon?
double d[4] = {0,1,2,3};
reinterpret_cast<double[2]>(d);
GCC declares it an invalid cast from type 'double*' to type 'double [2]'
and clang declares that reinterpret_cast from 'double *' to 'double [2]' is not allowed
Now in case the intent is not obvious, I would like this code to return a double[2] that contains {0,1}, pretty much like a reinterpret_cast<double*>(d)
would. (Hence I know it would work with pointers, so that's not what I'm asking)
The result of a reinterpret_cast cannot safely be used for anything other than being cast back to its original type. Other uses are, at best, nonportable. The reinterpret_cast operator cannot cast away the const , volatile , or __unaligned attributes.
Although the reinterpret_cast itself might be unspecified behaviour, attempting to access the parameters once you've done the cast is undefined behaviour.
None of the casts happen at compile time. You only have the data at runtime, in general.
What you may want is
double (&d2)[2] = reinterpret_cast<double(&)[2]>(d);
Not sure it is not pedantically undefined behavior though (as most usage of reinterpret_cast
).
Both compilers are correct.
reinterpret_cast
is not a hammer, it's a powerful precision tool. All uses of reinterpret_cast
have to involve at least one pointer or reference type as the source or as the destination, except for the degenerate case of an identity integral conversion (i.e. reinterpret_cast
from int
to int
is allowed and does nothing.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With