A typical use of a union - C Data Type

C examples for Data Type:union

Description

A typical use of a union

Demo Code

#include <stdio.h>

#define CHARACTER   'C'
#define INTEGER     'I'
#define FLOAT       'F'

struct currency{// www  .j  a  va  2s  .com
    char type;
    union flag {
        char   c;
        int    i;
        float  f;
    } shared;
};

void print_function( struct currency generic )
{
    printf("\n\nThe generic value is...");
    switch( generic.type )
    {
        case CHARACTER: printf("%c",  generic.shared.c);
                        break;
        case INTEGER:   printf("%d",  generic.shared.i);
                        break;
        case FLOAT:     printf("%f",  generic.shared.f);
                        break;
        default:        printf("an unknown type: %c\n",
                                generic.type);
                        break;
    }
}

int main( void ){
    struct currency var;

    var.type = CHARACTER;
    var.shared.c = '$';
    print_function( var );

    var.type = FLOAT;
    var.shared.f = (float) 1.67890;
    print_function( var );

    var.type = 'x';
    var.shared.i = 1;
    print_function( var );
    return 0;
}

Result


Related Tutorials