C Programming: Structure vs Union – What You Need to Know

In C programming, a structure (often referred to as struct) is a user-defined data type that allows the grouping of variables of different types under a single name. This feature is particularly useful for representing complex data records, where each record can contain a mix of integers, floating-point numbers, characters, arrays, and even other structures. For example, a structure can be used to represent a student’s record, combining their name, age, and grades into a single entity.

Defining a Structure

To define a structure in C, you use the struct keyword followed by the structure name and a block containing the member definitions. Each member of the structure can be of a different data type. Once defined, the structure can be used to declare variables of that type.

The syntax for defining a structure is as follows:

struct [structure_name]
{
    member1_type member1_name;
    member2_type member2_name;
    ...
    memberN_type memberN_name;
};

Example:

struct Student
{
    char name[50];
    int age;
    float marks;
};

In this example, Student is a structure type with three members: name (a character array), age (an integer), and marks (a float).

Alternatively, you can declare variables of the structure type at the time of defining the structure:

struct Student
{
    char name[50];
    int age;
    float marks;
} student1, student2;

This defines the structure and simultaneously declares two variables, student1 and student2, of type struct Student.

Unions in C

A union in C is another user-defined data type, similar to a structure, but with a key difference: while a structure allocates separate memory for each of its members, a union allocates a single shared memory location for all its members. This means that at any given time, a union can only store a value in one of its members. The size of the union is determined by the size of its largest member, and updating one member will overwrite the values of the other members.

Unions are particularly useful when you need to work with different types of data in the same memory location, thereby conserving memory.

Defining a Union

To define a union, you use the union keyword, similar to how structures are defined. The union contains multiple members, but only one of them can store a value at a time.

The syntax for defining a union is as follows:

union [union_name]
{
    member1_type member1_name;
    member2_type member2_name;
    ...
    memberN_type memberN_name;
};

Example:

union Data
{
    int i;
    float f;
    char str[20];
};

In this example, Data is a union with three members: an integer i, a float f, and a character array str. However, since all members share the same memory, you can only use one member at a time.

You can also declare variables of the union type at the time of defining the union:

union Data
{
    int i;
    float f;
    char str[20];
} data1, data2;

This declares two variables, data1 and data2, of type union Data.

Key Differences Between Structure and Union

  1. Memory Allocation: In a structure, each member has its own memory location, meaning the total memory allocated is the sum of all members. In contrast, a union allocates memory equal to the size of its largest member, as all members share the same memory location.
  2. Accessing Members: In a structure, all members can be accessed and modified independently at any time. In a union, only one member can hold a value at a time, and modifying one member will affect all other members.
  3. Use Cases: Structures are ideal for representing records and complex data types that require multiple, independent values. Unions are used when you need to store different types of data in the same memory space, depending on the context, thereby saving memory.

Example:

// C program to illustrate differences 
// between structure and Union 

#include <stdio.h> 
#include <string.h> 

// declaring structure 
struct struct_example { 
	int integer; 
	float decimal; 
	char name[20]; 
}; 

// declaring union 

union union_example { 
	int integer; 
	float decimal; 
	char name[20]; 
}; 

void main() 
{ 
	// creating variable for structure 
	// and initializing values difference 
	// six 
	struct struct_example s = { 18, 38, "Codemagnet" }; 

	// creating variable for union 
	// and initializing values 
	union union_example u = { 18, 38, "geeksforgeeks" }; 

	printf("structure data:\n integer: %d\n"
		"decimal: %.2f\n name: %s\n", 
		s.integer, s.decimal, s.name); 
	printf("\nunion data:\n integer: %d\n"
		"decimal: %.2f\n name: %s\n", 
		u.integer, u.decimal, u.name); 

	// difference two and three 
	printf("\nsizeof structure : %d\n", sizeof(s)); 
	printf("sizeof union : %d\n", sizeof(u)); 

	// difference five 
	printf("\n Accessing all members at a time:"); 
	s.integer = 183; 
	s.decimal = 90; 
	strcpy(s.name, "Codemagnet"); 

	printf("structure data:\n integer: %d\n "
		"decimal: %.2f\n name: %s\n", 
		s.integer, s.decimal, s.name); 

	u.integer = 183; 
	u.decimal = 90; 
	strcpy(u.name, "Codemagnet"); 

	printf("\nunion data:\n integer: %d\n "
		"decimal: %.2f\n name: %s\n", 
		u.integer, u.decimal, u.name); 

	printf("\n Accessing one member at time:"); 

	printf("\nstructure data:"); 
	s.integer = 240; 
	printf("\ninteger: %d", s.integer); 

	s.decimal = 120; 
	printf("\ndecimal: %f", s.decimal); 

	strcpy(s.name, "C programming"); 
	printf("\nname: %s\n", s.name); 

	printf("\n union data:"); 
	u.integer = 240; 
	printf("\ninteger: %d", u.integer); 

	u.decimal = 120; 
	printf("\ndecimal: %f", u.decimal); 

	strcpy(u.name, "C programming"); 
	printf("\nname: %s\n", u.name); 

	// difference four 
	printf("\nAltering a member value:\n"); 
	s.integer = 1218; 
	printf("structure data:\n integer: %d\n "
		" decimal: %.2f\n name: %s\n", 
		s.integer, s.decimal, s.name); 

	u.integer = 1218; 
	printf("union data:\n integer: %d\n"
		" decimal: %.2f\n name: %s\n", 
		u.integer, u.decimal, u.name); 
}

Output:

structure data:
 integer: 18
decimal: 38.00
 name: Codemagnet

union data:
 integer: 18
decimal: 0.00
 name: 

sizeof structure : 28
sizeof union : 20

 Accessing all members at a time:structure data:
 integer: 183
 decimal: 90.00
 name: Codemagnet

union data:
 integer: 1801807207
 decimal: 277322871721159507258114048.00
 name: Codemagnet

 Accessing one member at time:
structure data:
integer: 240
decimal: 120.000000
name: C programming

 union data:
integer: 240
decimal: 120.000000
name: C programming

Altering a member value:
structure data:
 integer: 1218
  decimal: 120.00
 name: C programming
union data:
 integer: 1218
 decimal: 0.00
 name: ?

In C programming, understanding the differences between structures and unions is essential for effective memory management and data organization. Both structures and unions allow you to group variables of different types, but they serve distinct purposes and have unique characteristics.

Structures provide a way to encapsulate multiple data types under one name, with each member having its own memory space. This makes structures ideal for creating complex data types, such as records, where you need to store and access multiple related pieces of information simultaneously.

Unions, on the other hand, allow multiple variables to share the same memory location, enabling you to store different data types in the same space at different times. This is particularly useful in situations where memory efficiency is critical, and you only need one of the variables to hold a value at any given time.

By choosing the appropriate data type—structure or union—based on your application’s requirements, you can optimize both memory usage and functionality. Understanding these differences empowers you to make informed decisions in your C programming projects, ensuring that your code is both efficient and effective.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>