0

For the following code

#include <iostream>

using namespace std;

union type
{
    int a;
    char b ;
};

int main()
{
    type first;
    first.b = 'a';
    cout << first.a << " " << first.b << endl;

}

the output is -858993567 a (MSVC) or 4201057 a(g++ MINGW).

but for

#include <iostream>

using namespace std;

union type
{
    int a;
    char b ;
};

int main()
{
    type first;
    first.a = 0;
    first.b = 'a';
    cout << first.a << " " << first.b << endl;

}

the output is 97 a

And these values are fixed under every circumstances (tried rebooting and creating new workspace/file, hence not garbage values).

So, why did the initialization (in the second case) made a difference?

I have tried it both on visual studio (using MSVC) and visual studio code (using g++).

Update 1 I checked on online IDE which probably use Linux g++, and they give the exact expected answer i.e., 97 a, in both the cases.

Abhay Patil
  • 389
  • 5
  • 19

2 Answers2

-3

If you specify first.a in first code sample - you will get fixed, stable value.

You have union with 4 bytes size and initialize only one byte of them.

Evgeny
  • 1,072
  • 6
  • 6
-3

Union is like type who can holds any type but this types musts be writed in definition of union, like this:

union Example {

    char a;
    std::int32_t b;

};

Example ex; /// Create object of union
ex.a = 'c'; /// At this moment a member is valid and b is invalid
std::cout << ex.b; /// This cause undefined behavior

Be aware, size of union object is size of type who need most bytes. In this case size is same as size of b property.