Understanding the Difference Between Structure And Union, with Examples

StockEU / Shutterstock.com

Programming languages have many data types at their disposal. Structures and unions are important data structures when using theCorC++ 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 structures and unions in the C andC++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 amemberof the struct. Unlike arrays, structure members of the struct can be of many differentdata 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, butonly 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: %d\n", sA.numA);   // Print values of numA and letterA
  printf("My letter: %c\n", 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 : %s\n", A.WebSiteName);
    strcpy( A.WebSiteSubject, "Consumer Technology and Programming");    
    printf( "Website Subject: %s\n", A.WebSiteSubject);
    A.WebSiteAuthors = 200;
    printf( "Number of Website Authors : %d\n", 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 canonly 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 canuse any Cor 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 structures and unions also use the (.) operator to access variables within thedata structure.

Pass-By-Value and Return-By-Value

Both structures and unions are able to be passed-by-valueandreturned-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 bothuser-defineddata types as opposed to built-in data types. Built-in data types are declared and definedwithin the code librarywhile user-defined data types are declared and defined by the userwithin 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

Structuresallocate memoryfor the structurewithinthe structure itself. The size of a structure is greater than or equal tothe sum of all the members sizes. Unions allocate memoryup to the size of the largest union member. Thus, the size of a union is greater than or equal tothe 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 ofallunion members.

Initializing Member Variables

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

Final Thoughts

Structures and unions are 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.

Leave a Comment