-1

I have code like this:

const quint8* data[2];    
const float *p0 = (float*)data[0]

In QtCreator, I am getting a warning:

"use of old-style cast".

I tried to write it like this:

const float *p0 = const_cast<float*>(data[0])

But I'm getting another error that between the types cannot be casted.

What should be the right syntax?

0xCursor
  • 2,242
  • 4
  • 15
  • 33
JeCh
  • 980
  • 1
  • 7
  • 14

1 Answers1

7

Ok so this is the answer:

const float *p0 = reinterpret_cast<const float*>(data[0]);

BUT be extremely careful of the C++ strict aliasing rules. Their implication for your example is that you can legally access via p0 if and only if data[0] points to a float object. For instance

This is legal

const float f = 24.11f;

const quint8* data[2] {};

data[0] = reinterpret_cast<const quint8*>(&f);
// for the above line:
// data[0] can legally alias an object of type float
//    if quint8 is typedef for a char type (which is highly likely it is)
// data[0] now points to a float object

const float *p0 = reinterpret_cast<const float*>(data[0]);
// p0 points to the float object f. Legal

float r = *p0; // legal because of the above

return r;

And this is illegal:

const quint8 memory[4]{};
memory[0] = /* ... */;
memory[1] = /* ... */;
memory[2] = /* ... */;
memory[3] = /* ... */;

const quint8* data[2] {};

data[0] = memory;
// data[0] doesn't point to a float object

const float *p0 = reinterpret_cast<const float*>(data[0]);
// no matter what trickery you use to get the cast
// it is illegal for a `float*` pointer to alias a `quint8[]` object

float r = *p0; // *p0 is illegal and causes your program to have Undefined Behavior
bolov
  • 72,283
  • 15
  • 145
  • 224