Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is union declaration in C?

Samia Ishaque

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

Variable declaration in C usually means that you have to highlight the datatype and its size to the compiler. This limits you to one data type at a time. However, union is a distinct data type in C that lets you store variables of different data types in the same memory location. Unions are defined similarly to structs. This is shown below:

union UnionName{ //union tag
datatype variable_name;
datatype variable_name;
datatype variable_name;

}UnionVariable; //union variable

Union has multiple members that are each of a different data type. However, only one member contains a value at any given time. Hence, a union variable’s size is as big as the biggest member in its declaration.

Examples

Below is an example that demonstrates how only one member holds a value at a time as one.i prints a garbage value after a float value is stored in one.j:

#include <stdio.h>
union Example{ //union tag
int i; //union member
float j;
}one; //union variable
int main() {
one.i = 10;
one.j = 20.2;
//union members can be accessed using (.) operator
printf("variable i: %d\n", one.i);
printf("variable j: %f\n", one.j);
return 0;
}

The example below demonstrates that the size of a union variable is equal to the largest member:

#include <stdio.h>
union Example { //union tag
int i; //union member
float j;
char s[20];
}one;
int main() {
union Example one; // another way to declare union variable
printf("size of variable one: %ld\n", sizeof(one));
return 0;
}

RELATED TAGS

c

CONTRIBUTOR

Samia Ishaque
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring