Displaying union members' values and show its weakness compared to struct


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Displaying union members' values and show the weakness compared to the struct construct

To show: The union aggregate data type C/C++ program example showing its weakness compared to struct




// This example is C++

// union data type

#include <iostream>

using namespace std;


union sample


int p;

float q;

double r;



void main(void)


// union data type

union sample content;

content.p = 37;

content.q = 1.2765;


cout<<"Display the union storage content\n";

cout<<" ONLY one at a time!\n";


cout<<"Integer: "<<content.p<<"\n";

cout<<"Float : "<<content.q<<"\n";

cout<<"Double : "<<content.r<<"\n";

cout<<"See, some of the contents are rubbish!\n";

content.q = 33.40;

content.r = 123.94;

cout<<"\nInteger: "<<content.p<<"\n";

cout<<"Float : "<<content.q<<"\n";

cout<<"Double : "<<content.r<<"\n";

cout<<"See another inactive contents, rubbish!\n";

cout<<"\nBetter use struct data type!!\n";



Output example:


Display the union storage content

ONLY one at a time!


Integer: 1067672666

Float : 1.2765

Double : -9.25596e+061

See, some of the contents are rubbish!

Integer: -171798692

Float : -4.93268e+032

Double : 123.94

See another inactive contents, rubbish!

Better use struct data type!!

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index