Unions

Unions are very similar to structs, but the data shares the same memory spaces, so they cannot be used at the same time.

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.


Unions

#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!


Source: Derrick Robinson, http://cpp.tech-academy.co.uk/unions/
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License.

Last modified: Tuesday, August 31, 2021, 10:52 AM