Home

 › 

Articles

 › 

Understanding the Difference Between Structure and Union, with Examples

Dynamic memory allocation

Understanding the Difference Between Structure and Union, with Examples

Key Points

  • Structures, or structs, are user-defined data types that group variables together, allowing for different data types within the struct
  • Unions are similar to structures but use fewer resources, storing multiple data types in one memory location
  • Both structures and unions can use any C or C++ data type, have the same limited set of operators, and can be passed-by-value and returned-by-value
  • Structures allocate memory for each member, while unions allocate memory for the largest member only
  • Structures can initialize and access all members at once, while unions can only initialize and access one member at a time

Programming languages have many data types at their disposal. Structures and unions are important data structures when using the C or C++ languages. Initially, they can seem pretty similar. However, when you understand the difference between them, you can use them to optimize your code and build programs. Let’s take a look at the differences between structure and union in the C and C++ programming languages.

What Is a Structure?

A structure, also known casually and in code as a struct, is a user-defined data type used to group several variables together in one place. Each variable in the struct is referred to as a member of the struct. Unlike arrays, structure members of the struct can be of many different data types (char, int, float, etc.), making structs an excellent and efficient way to sort variables of many data types.

What Is a Union?

Unions are also user-defined data types that are similar to structures but use fewer resources. Unions allow the user to store multiple data types in one location in the memory. With unions, you can define and store multiple data types in the same location in memory, but only one member of the union can have a value at any given time.

How to Define a Structure

Structures are defined in the code using the struct statement. The struct statement defines a new data type that is more than or equal to one member. You can use the following pseudocode to define a structure in your code.

struct [structure name] // Define structure
   {
       member definition; // Define member
       member definition;
       ...
       member definition;
   }; // End structure
   (OR)
   struct [structure name] // Define structure
   {
       member definition; // Define member
       member definition;
       ...
       member definition;
   }structure variable declaration; // Define structure variable name

To define a struct, first, you use the struct statement followed by the structure name. Then you’ll place each member and its respective definition between the brackets, defining them in the structure. You can define a variable for the entire structure at the end, but this is unnecessary.

struct StructureA {   //Delcare structure
  int numA;           // Member (int)
  char letterA;       // Member (char)
}; // End of Structure designated by semicolon
(OR)
struct StructureA { // Define structure
	int numA; // Member (int)
	char letterA; // Member (char)
}StructA; // Defines the structure with the variable StructA

How to Define a Union

Unions are defined with the same syntax as structures, but the statement you need to use is union. The following pseudocode can be applied to any situation where you must define a union in your code.

union [union name] // Define union
    {
       member definition; // Define member
       member definition;
       ...
       member definition;
    }; // End union with semicolon
    (OR) 
    union [union name] // Define union
    {
       member definition; // Define member
       member definition;
       ...
       member definition;
    }union variable declaration; // Define union variable name

To define a union, you begin the block by using the union statement. Then you’ll need to define each member of the union in its own line of code, ending each with a semicolon. Finally, you’ll need to end the union with a semicolon. You can also define a union variable name, which is unnecessary, just like with structures. 

union unionA // Define union
{
    char  charA[50]; // Define member
    int   numA;
};
(OR)
union unionA // Define union
{
    char  charA[50]; // Define member
    int   numA;
} unA; // Define union variable name

How to Access a Structure

Accessing a structure requires first initializing values for the structure’s members. The following code creates, initializes, and accesses a structure. We’ll explain the code in more detail following the code block.

// Create a structure called structureA
struct structureA {
  int numA;
  char letterA;
};
int main() {
  struct structureA sA;   // Create a structure variable of structureA called sA
  sA.numA = 10;  // Assign values to members of sA
  sA.letterA = 'A';
  printf("My number: %dn", sA.numA);   // Print values of numA and letterA
  printf("My letter: %cn", sA.letterA);
  return 0;
}

First, we start by defining the structure we’ll access with our code. In this case, we’ve made a structure called structureA. We’ll define two variables within the structure, numA and letterA. Then we define a structure variable, sA, that we’ll use to access the variables within structureA. Now we want to initialize variables for sA.numA and sA.letterA, in this case, the integer number 10 and the letter A. Finally, we can access the variables with the printf function.

How to Access a Union

Accessing a union is roughly similar to accessing a structure. However, it’s important to remember that when using a union, only one variable can be accessed and initialized at a time. This is the primary difference between the two data types and it will be reflected in the code.

union WebSites
{
    char  WebSiteName[50];
    char  WebSiteSubject[50];
    int   WebSiteAuthors;
};
void main( )
{
    union WebSites A;
    strcpy( A.WebSiteName, "History-Computer");   
    printf( "Website Name : %sn", A.WebSiteName);
    strcpy( A.WebSiteSubject, "Consumer Technology and Programming");    
    printf( "Website Subject: %sn", A.WebSiteSubject);
    A.WebSiteAuthors = 200;
    printf( "Number of Website Authors : %dn", A.WebSiteAuthors);
}

In this code block, we start by defining a union called “WebSites.” This union has two character strings that can store up to fifty characters and an integer. In this case, the character strings are designed to store website names, and the integer represents how many authors are assigned to the website. Next, we’ll initialize a variable A for WebSites to allow us to access the variables within the union. Finally, we’ll alternate accessing and initializing the variables and then printing the results. Since unions can only access one variable at a time, you can’t assign values to all of them and then print them as blocks. Each block must initialize, assign, and then print to get all the values printed to the console.

Similarities

Usable Data Types

Structures and unions are usable with the same data types. Both structures and unions can use any C or C++ data type within their member sets, including additional structures and unions. Bit fields are also an option for members of structures and unions.

Usable Operators

Structures and unions use the same limited set of operators. Both must be assigned to variables using the (=) operator, and their sizes can only be changed using the “sizeof” operator. Structures and unions must be assigned to variables of the same type. Both structure and union also use the (.) operator to access variables within the data structure.

Pass-By-Value and Return-By-Value

Both structures and unions are able to be passed-by-value and returned-by-value. To pass or return-by-value, you’ll need to use an argument that is of the same type as the function parameter. Structures and unions are passed-by-value like a scalar variable.

Function Type

Structures and unions are both user-defined data types as opposed to built-in data types. Built-in data types are declared and defined within the code library while user-defined data types are declared and defined by the user within the code.

C++ vs. JavaScript
Structure and union are two important data structures in both the C and C++ programming languages.

©Wright Studio/Shutterstock.com

Differences

Keywords

Structures use the “struct” keyword to declare and define the structure. Unions use the “union” keyword to declare and define the union.

Memory Allocation

Structures allocate memory for the structure within the structure itself. The size of a structure is greater than or equal to the sum of all the members’ sizes. Unions allocate memory up to the size of the largest union member. Thus, the size of a union is greater than or equal to the size of the largest union member.

Alterations and Access to Members in Memory

When you make alterations to the values of structure members, the values of the other structure members aren’t altered because multiple members of a structure can be accessed at once. Since unions can only access one member at a time, altering the value of a union member alters the values of all union members.

Initializing Member Variables

Structures can initialize every member of the structure all at once. Unions can only initialize the first member of the union.

Final Thoughts

Using structure and union is an excellent way to up your game in C and C++. These data types can help you organize and optimize your code to build better and more complex programs. Let us know if this guide helped you learn something new about C and C++! We love to hear from our readers in the comments and on social media.

Summary Table

AspectStructureUnion
Keywordsstructunion
Memory AllocationAllocates memory for the structure itselfAllocates memory for the largest member
Alterations and Access to MembersMultiple members can be accessed at onceOnly one member can be accessed at a time
Initializing Member VariablesCan initialize every memberCan only initialize the first member

Frequently Asked Questions

What programming languages use structures and unions?

Structures and unions are used in the C and C++ programming languages.

What are structures and unions?

Structures and unions are data types used to store groups of variables and other data of many different types.

How do structures and unions differ from arrays?

Arrays can only store data of the same type (i.e. multiple integers.) Structures and unions can store elements of multiple types in the same structure or union.

What are the differences between structures and unions?

Structures and unions have different statement keywords, memory allocation, value alteration, and accessibility, and initialization.

What are the similarities between structures and unions?

Both structures and unions can store multiple data types, including bit fields, have the same assignment operators, can be passed and returned by value, and use the same selection operator.

To top