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.