Unions

Unions are similar to structures but only one member within the union can be used at a time, due to it having a shared memory size for all members.

 

union identifier {

char desc[50] ;
float price ;
int devs ;
} ;

 

Unions are used when just one condition will be applied and only one variable is required.

 

#include <iostream>
using namespace std ;

union opSysName {
	char desc[50];
	float price;
	int devs;
} ;

int main() {

	union opSysName linux = {"fun, free and better!"} ;
	cout << "The best OS might just possibly be " << linux.desc ;

	/*set price - remembering that a union can only hold one variable at a time*/
	linux.price = 0.01 ;
	cout << " It costs less than $" << linux.price ;

	linux.devs = 1200 ;
	cout << " and has about " << linux.devs << " developers on each release!" << endl << endl ;

	union opSysName windows = {"restrictive, proprietary and monopolistic!"} ;

	cout << "A certain other consumer OS is generally " << windows.desc ;

	windows.price = 99.99 ;

	cout << " It costs too much, i.e £" << windows.price ;

	windows.devs = 1138 ;

	cout << ", and has around " << windows.devs << " developers trying to make it work!" ;

	return 0;
}

Compile & Run:

The best OS might just possibly be fun, free and better! It costs less than $0.01 and has about 1200 developers on each release! 

A certain other consumer OS is generally restrictive, proprietary and monopolistic! It costs too much, i.e £99.99, and has around 1138 developers trying to make it work!

Leave a Reply