C Union Example - C

What is union in C programming?

Snippet Code


  
Rate this page :
  [ 0 votes]

In C program union refers to variables which enables you to store different data types in same memory location. Here, you will get two different outputs. In first output where number and value will get corrupted because the memory is occupied by the 3rd variable str. In second output all the members getting printed very well because one member is being used at a time. The sample C union code is given below.

#include <stdio.h> #include <string.h> union demodata { int num; float val; char str[20]; }; int main( ) { union demodata data; data.num = 10; data.val = 220.5; strcpy( data.str, "Hscripts"); printf( "data.num : %dn", data.num); printf( "data.val : %fn", data.val); printf( "data.str : %sn", data.str); printf("********n"); data.num = 10; printf( "data.num : %dn", data.num); data.val = 220.5; printf( "data.val : %fn", data.val); strcpy( data.str, "Hscripts"); printf( "data.str : %sn", data.str); return 0; }

Tags


Ask Questions

Ask Question