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;
}
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;
}
&(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;
goes like this (i think:)):
looks about right?