- C Programming Tutorial
- C - Home
- C - Overview
- C - Features
- C - History
- C - Environment Setup
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Tokens
- C - Keywords
- C - Identifiers
- C - User Input
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Integer Promotions
- C - Constants
- C - Literals
- C - Escape sequences
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - if statement
- C - if...else statement
- C - nested if statements
- C - switch statement
- C - nested switch statements
- C - Loops
- C - While loop
- C - For loop
- C - Do...while loop
- C - Nested loop
- C - Infinite loop
- C - Break Statement
- C - Continue Statement
- C - goto Statement
- C - Functions
- C - Main Functions
- C - Return Statement
- C - Recursion
- C - Scope Rules
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays
- C - Pointers
- C - Pointer Arithmetics
- C - Passing Pointers to Functions
- C - Strings
- C - Array of Strings
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Pointers to Structures
- C - Self-Referential Structures
- C - Nested Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
C - Unions
The union keyword in C lets you define a derived data type, very mush similar to the struct keyword. A union data type in C also that allows to store different data types in the consecutive memory location. However, unlike a struct variable, a variable of union type, only one of its members can contain a value at any given time, whereas a struct variable stores values of all the elements.
Defining a Union
To define a union, you must use the union keyword in the same way as you did while defining a structure. The union keyword defines a new data type with more than one member for your program. The format of the union statement is as follows −
union [union tag] { member definition; member definition; ... member definition; } [one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables.
Here is a definition of union type called myunion −
union myunion{ int a; double b; char c; };
It may be noted that the definition of union is similar to the definition of struct. A definition od struct type mystruct with the same elements looks like this −
struct mystruct{ int a; double b; char c; };
The main difference between struct and union is the size of the variables. The compiler allocates the memory to a struct variable, to be able to store values for all the elements. In mystruct, there are three elements one each int, double and char, requiring 13 bytes (4+8+1). Hence,
sizeof(struc mystruct)
returns 13.
On the other hand, for a union type variable, the compiler allocates a chunk of memory of the size enough to accommodate the element of largest byte size. The myunion type has an int, double and a char element. Out of which the size of double is the largest − 8. Hence,
sizeof(union myunion)
returns 8.
Another point to take into consideration, is that a union variable can hold value of only one its elements. When you assign value to one element, the other elements are undefined. If you try to use, it will result in some garbage.
Let us first initialize a mystruct variable −
struct mystruct{ int a; double b; char c; } s1; s1 = {10, 10.50, 'A'};
The memory allocation is done as follows −
10 | 10.50 | A |
int (4 bytes) | double (8 bytes) | Char (1 byte) |
On the other hand, when a myunion variable is created, you can either assign value to a, or b or c. Total memory allocated to myunion variable is 8 bytes. If it holds an int, remaining 4 bytes will be unused. If you hold a char, the remaining 7 bytes will be garbage.
union myunion{ int a; double b; char c; } u1;
Initialize the int element
u1.a = 10;
The other elements become garbage
10 | ||||
u1.a (int element) | garbage |
When a double element is assigned, the entire allocated memory is occupied by u1.b as it is the element with largest size
u1.b=10.50;
The entire memory allocated is occupied and there is no garbage deposited.
10.50 |
u1.b |
However, when you assign value to the char element,
u1.c = 'A';
A | |||||||
garbage | u1.c |
Example
In the code below, we define a union type named Data having three members i, f, and str −
union Data { int i; float f; char str[20]; } data;
Now, a variable of Data type can store an integer, a floating−point number, or a string of characters. It means a single variable, i.e., same memory location, can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string. The following example displays the total memory size occupied by the above union −
Example
#include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main(){ union Data data; printf( "Memory size occupied by data : %d\n", sizeof(data)); return 0; }
When the above code is compiled and executed, it produces the following result −
Output
Memory size occupied by data : 20
Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union type. The following example shows how to use unions in a program −
Example
#include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main() { union Data data; data.i = 10; data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); printf( "data.str : %s\n", data.str); return 0; }
When the above code is compiled and executed, it produces the following result −
Output
data.i : 1917853763 data.f : 4122360580327794860452759994368.000000 data.str : C Programming
Here, we can see that the values of i and f members of union shows garbage because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having unions −
Example
#include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main(){ union Data data; data.i = 10; printf( "data.i : %d\n", data.i); data.f = 220.5; printf( "data.f : %f\n", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %s\n", data.str); return 0; }
When the above code is compiled and executed, it produces the following result −
Output
data.i : 10 data.f : 220.500000 data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.