1

Kindly explain me the line containing variable i initialization does

struct vector
{
   float value;
};

int main()
{
    vector v3;
    v3.value = 5.0f;

    float i = *(float*)&(v3);

    return 0;
}
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
user3851992
  • 13
  • 1
  • 3

2 Answers2

6
&(v3)

This takes the address of v3 which is of type vector*.

(float*)&(v3)

Now we cast that address to be of type float*.

*(float*)&(v3)

Finally, we read the contents of that float* and initialize i with the value.

The validity of this rather convoluted process is covered here: Does accessing the first field of a struct via a C cast violate strict aliasing? In summary however, for the specific scenario described in the question, using a POD struct, the standard says that the cast is valid.

It would make much more sense to write

float i = v3.value;
Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Note this is legal due to 9.2 [Class.mem]/20: "A pointer to a standard-layout struct object, suitably converted using a `reinterpret_cast`, points to its initial member [...] and vice versa." This had to be possible in `C` to achieve an approximation of inheritance. – BoBTFish Jul 18 '14 at 09:04
0

goes like this (i think:)):

  1. you took v3, and asked for it's address (& operator)
  2. then cast it into a (float*)
  3. finally, you asked for it's content (* operator), and assigned it to i

looks about right?

eiran
  • 1,378
  • 15
  • 16