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)
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.)