Hello readers, welcome to our blog. In the last article, you had learnt about the Structures In C Programming Language. I hope you all understood how to use a structure in c, how to define structures and how to access structures member functions but in today’s article, you will learn how to declare a Union in c programming language. So let’s start.
Introduction to Union in c programming language
C programming language provides you with a special data type. This data type is called Union In C Programming Language. With Union in c, you can store many types of data types in the same memory location. You can create many variables of different data types inside the unions. But at one time the value can be stored in the same variable. With Unions, you can use the same memory location in many ways.
Unions are similar to structures in c language. Just the difference is that every member of the structure occupies a separate memory location and the size of them all is different. But all members of the union use the same memory location and its size is the same as the largest size member.
Defining a Union in c programming language
Accessing Union Member Variables
in.a = 10;
If you want to print any union member, then you can do this as follows.
A Complete Example of Union In C Programming Language
If you try to print all the members of the union together by assigning values together then the output will be an invalid show. When you assign the value to another variable after one, the value in memory will remain the same.
In simple words, the member who will be initialized in the last will be stored in the value memory.
in.a = 15;
printf(“Value of a is : %d\n”,in.a);
in.b = 20;
printf(“Value of b is : %f”,in.b);
Value of a is : 15
Value of b is : 20.00000