Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is reinterpret_cast to C-style array illegal C++11?

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)

like image 235
Gurg Hackpof Avatar asked Aug 29 '13 15:08

Gurg Hackpof


People also ask

Is it safe to use reinterpret_cast?

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.

Is reinterpret_cast undefined Behaviour?

Although the reinterpret_cast itself might be unspecified behaviour, attempting to access the parameters once you've done the cast is undefined behaviour.

Is reinterpret cast compile time?

None of the casts happen at compile time. You only have the data at runtime, in general.


2 Answers

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

like image 124
Jarod42 Avatar answered Oct 17 '22 23:10

Jarod42


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

like image 4
R. Martinho Fernandes Avatar answered Oct 18 '22 00:10

R. Martinho Fernandes