ADVERTISEMENT
ADVERTISEMENT

C program to declare, initialize an union, example of union

In this program, we will learn to declare, initialize an union in C programming languages, how to assign the values to union elements and how to access assigned values through union object?

/*C program to declare, initialize an UNION, example of UNION*/

#include <stdio.h>

// union declaration
union pack{
char a;
int	b;
double c;
};


int main()
{
	
	pack p; //union object/variable declaration

	printf("\nOccupied size by union pack: %d",sizeof(pack));

	// assign value to each member one by one other it will replace last value
	p.a='A';
	printf("\nValue of a:%c",p.a);

	p.b=10;
	printf("\nValue of b:%d",p.b);
	
	p.c=12345.6790;
	printf("\nValue of c:%f",p.c);

	// see, what will happen? if u will assign values together
	p.a='A';
	p.b=10;
	p.c=12345.6790;

	// here the last value of p.c will be accessed by all members
	printf("\nValue of a:%c, b:%d, c:%f",p.a,p.b,p.c);

	return 0;
}

Output

Occupied size by union pack: 8
Value of a:A
Value of b:10 
Value of c:12345.679000 
Value of a:�, b:-377957122, c:12345.679000

C Structure & Union Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.