Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a union always have default value of zero?

Tags:

c++

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.


2 Answers

Does a union always have default value of zero?

The language standard says this:

If an object that has static or thread storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
  • if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

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 a struct rather than a union. But note that the two code examples are very different because the union in this first has static storage duration and in the second the union has automatic storage duration. This results in completely different semantics for uninitialized variables.

like image 66
David Heffernan Avatar answered Sep 03 '25 23:09

David Heffernan


This is initializing the union variable :

union{
  float x;
  int i;
}u;
u.x=x;

meaning both x and i in the union are initialized.

like image 39
BЈовић Avatar answered Sep 03 '25 23:09

BЈовић



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!