C Union Declaration 🎯

beginner
7 min

C Union Declaration 🎯

Welcome to our deep dive into C Union Declaration! In this lesson, we'll explore this powerful feature of C programming that allows us to combine data of different types in a single variable. Let's get started!

Understanding the Basics 📝

Before we dive into unions, let's quickly review some basic concepts:

  • Data Types: In C, there are various data types like int, char, float, etc. Each data type has a specific size and is used to store different kinds of data.

Now, imagine a situation where you need to store data of different types in a single variable. That's where unions come into play!

Introduction to Union 💡

A union is a compound data type in C that lets you store different types of data in the same memory location. You can think of a union as a variable that can change its identity. It saves memory by allowing multiple variables to share the same space, which is useful when you need to store different types of data in a single place.

Union Syntax 📝

The syntax for union in C is simple:

c
union unionName { dataType1 varName1; dataType2 varName2; ... };

Here, unionName is the name of the union, and dataType represents the type of data that can be stored in the union.

Union Example 💡

Let's see a simple example of a union that stores both an integer and a floating-point number:

c
#include <stdio.h> union Data { int i; float f; }; int main() { union Data myData; myData.i = 42; printf("Integer value: %d\n", myData.i); // Prints: Integer value: 42 myData.f = 3.14; printf("Float value: %.2f\n", myData.f); // Prints: Float value: 3.14 return 0; }

In this example, we define a union Data with two variables: i (of type int) and f (of type float). When we assign a value to either myData.i or myData.f, we're actually modifying the same memory location.

Union Size 📝

The size of a union in C is equal to the size of its largest member. This is because the union reserves the size of its largest member to store data of any type.

Using Unions in Real Projects 💡

Unions are especially useful when memory management is crucial, such as in operating systems and embedded systems. They can help save memory by allowing different data types to share the same memory location.

Union Quiz 🎯

Quick Quiz
Question 1 of 1

What is the purpose of a union in C?

That's it for our introduction to C Union Declaration! In the next lesson, we'll dive deeper into unions, exploring more examples and advanced use cases. Stay tuned! 📝