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.
This is initializing the union variable :
meaning both
x
andi
in the union are initialized.General note: warning - you seem to be expecting that the int member somehow has the same size as the float member of the union. This might be true, but need not. You also seem to assume that your compiler uses a certain floating point representation. To my knowledge, the compiler has no such obligation2
just means that you should not really be using anonymous union types for externally visible symbols. This is a warning that you'll see locally too, if you compiled with
-Wall
(all warning on).As far as I can see from the code shown,
u.i
is NOT uninitialized. It is initialized per the fact that you assignedu.x
. This is the actual definition of a union: a union stores the member fields at the same memory location. This means, that even thoughu.i
might (haven't checked) be auto-initialized at 01 then you'll have overwritten it by assigning tou.x
1 (unlikely, because how would the compiler choose whether to 0-initialize .i or .x?)
2 though in practice most will use IEEE formats (http://en.wikipedia.org/wiki/IEEE_754) due the fact that most processors support that natively
The language standard says this:
So, in your first code sample,
u.i
will be initialised to zero.I'm not sure about the second code sample at all. I cannot see the point of the
union
there. I rather suspect that you meant to use astruct
rather than aunion
. But note that the two code examples are very different because theunion
in this first has static storage duration and in the second theunion
has automatic storage duration. This results in completely different semantics for uninitialized variables.