In C++, structures and unions are user-defined data types that allow you to store multiple data types together. Structures are versatile and commonly used for representing real-life objects, while unions share memory among their members, making them useful for memory-efficient programming.
Defining Structures and Accessing Members
A structure groups variables of different types under a single name. Each variable within a structure is called a member.
Syntax:
Person
structure and accessing its members.In this example:
- We define a structure
Person
with membersname
,age
, andheight
. person1
is an instance ofPerson
. We assign values to its members and display them.
Array of Structures
An array of structures allows you to store multiple instances of a structure in a single array. This is useful for managing data sets, such as a list of people or products.
Example: Array of Person
structures.
In this example:
- We create an array
people
ofPerson
structures and initialize it. - We then iterate through the array to display each person’s information.
Structures within Structures
Structures can contain other structures as members, allowing for more complex data representations.
Example: A Student
structure that contains a nested Address
structure.
In this example:
Address
is a nested structure within theStudent
structure.- We access the nested structure’s members using dot notation.
Introduction to Unions
A union is similar to a structure, but its members share the same memory location. This means only one member can hold a value at any time, which can be helpful when conserving memory.
Syntax:
In this example:
- When
floatVal
is assigned a value, it overwritesintVal
as they share the same memory location. - Accessing
intVal
after assigning tofloatVal
shows unexpected data becauseintVal
no longer holds a valid value.
Key Differences between Structures and Unions:
- Memory Allocation: In a structure, each member has its own memory location, while in a union, all members share the same memory space.
- Usage: Structures are useful for representing records, while unions are helpful in memory-sensitive scenarios where only one value is stored at a time.
Enumerations (Enums)
An enumeration is a user-defined data type that assigns names to integral constants, making code more readable. Enums are commonly used to define a set of related constants like days of the week or error codes.
Syntax:
In this example:
- The
Day
enum defines constants for each day of the week. - We assign
Wednesday
totoday
and check if it matchesWednesday
.
Benefits of Enums:
- Enums improve code readability by replacing magic numbers with meaningful names.
- They help in preventing invalid values by restricting variables to specific constants.