Saving memory with union - C++ Data Type

C++ examples for Data Type:union

Description

Saving memory with union

Demo Code

#include <iostream>
using namespace std;
// The union will be the size of a double, since that's the largest element
union Packed { // Declaration similar to a class
    char i;/*w  w  w .j  a v a2 s. c  o  m*/
    short j;
    int k;
    long l;
    float f;
    double d;
};
int main() {
    cout << "sizeof(Packed) = " << sizeof(Packed) << endl;
    Packed x;
    x.i = 'c';
    cout << x.i << endl;
    x.d = 3.14159;
    cout << x.d << endl;
}

Result


Related Tutorials