Please let us consider following code:
#include <iostream>
using namespace std;
union{
int i;
}u;
int main(){
int k=5;
cout<<k+u.i<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
This code shows me output 5,what means to me is that,variable i in union structure has default value=0, but the same code on ideone.com shows warning like this
prog.cpp:6: warning: non-local variable ‘<anonymous union> u’ uses anonymous type and then prints 5 as well, and last one core of this problem comes from algorithm calculate
Reciprocal of the square root and here is code
#include<iostream>
#include<math.h>
using namespace std;
float invsqrt(float x){
float xhalf=0.5f*x;
union{
float x;
int i;
}u;
u.x=x;
u.i=0x5f3759df-(u.i>>1);
x=u.x*(1.5f-xhalf*u.x*u.x);
return x;
}
int main(){
float x=234;
cout<<invsqrt(x)<<endl;
return 0;
}
It shows me output also,but my question is that is it a this code good?i meant that because int i is not initailized ,can any compiler consider it’s value as zero?i am curious and please tell me something about this,also if something is not clear from my question say me,i am not English native speaker.
The language standard says this:
So, in your first code sample,
u.iwill be initialised to zero.I’m not sure about the second code sample at all. I cannot see the point of the
unionthere. I rather suspect that you meant to use astructrather than aunion. But note that the two code examples are very different because theunionin this first has static storage duration and in the second theunionhas automatic storage duration. This results in completely different semantics for uninitialized variables.