联合体的典型用法

#include stdio.h#define CHARACTERC#define INTEGERI#define FLOATF

编程学习网为您整理以下代码实例,主要实现:联合体的典型用法,希望可以帮到各位朋友。

#include <stdio.h>

#define CHaraCTER   'C'
#define INTEGER     'I'
#define float       'F'

struct currency{
    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;
}
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐