The union data type C++ program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

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 some values from the union aggregate type in C++ program

To show: How to use the C/C++ union data type

 

// The union data type

#include <iostream>

using namespace std;

 

union Num

{

int ValueI;

float ValueF;

double ValueD;

char ValueC;

};

 

void main(void)

{

// Optional union keyword

// ValueI = 100

Num TestVal = {100};

 

cout<<"\nInteger = "<<TestVal.ValueI<<endl;

TestVal.ValueF = 2.123L;

cout<<"Float = "<<TestVal.ValueF<<endl;

cout<<"Uninitialized double = "<<TestVal.ValueD<<endl;

cout<<"Some rubbish???"<<endl;

TestVal.ValueC = 'U';

cout<<"Character = "<<TestVal.ValueC<<endl;

}

 

Output example:

 

Integer = 100

Float = 2.123

Uninitialized double = 5.30754e-315

Some rubbish???

Character = U

Press any key to continue . . .

 

 

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