Program to demonstrate usage of unions in C

#include <stdio.h>
 
union item {
    char cvalue;
    int ivalue;
    float fvalue;
    double dvalue;
};
int main()
{
    union item value;
 
    value.cvalue='C';
    printf("cvalue=%c, address=%un",value.cvalue,&value.cvalue);
 
    value.ivalue=58;
    printf("ivalue=%d, address=%un",value.ivalue,&value.ivalue);
 
    value.fvalue=79.0;
    printf("fvalue=%f, address=%un",value.fvalue,&value.fvalue);
 
    value.dvalue=3849.273;
    printf("dvalue=%g, address=%un",value.dvalue,&value.dvalue);
 
    printf("nNew Values...n");
 
    printf("cvalue=%c, address=%un",value.cvalue,&value.cvalue);
    printf("ivalue=%d, address=%un",value.ivalue,&value.ivalue);
    printf("fvalue=%f, address=%un",value.fvalue,&value.fvalue);
    printf("dvalue=%g, address=%un",value.dvalue,&value.dvalue);
 
    return 0;
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.