Difference Between Structure and Union in C Language

Difference Between Structure and Union in C Language

24 Jun 2024
Intermediate
242 Views
7 min read
Learn via Video Course & by Doing Hands-on Labs

Free C Programming Online Course With Certificate

Structure and Union in C Programming

Do you know C language can store elements of the same as well as different data types? Arrays store the same data type elements while structure and union store different data type elements. Structure and Union are user-defined data types in C. Both store elements of different data types of varying sizes.

In this C tutorial, we'll study the difference between structure and union with examples in C programming.

Read More: Top 50 Mostly Asked C Interview Questions and Answers

What is a Structure in C?

The structure is a user-defined data type declared with a "struct" keyword. It combines different datatypes into a single datatype under one name. All the elements of a structure are stored at contiguous memory locations. The total memory size of a structure is the sum of the sizes of all its elements. You can access the structure elements using the dot (.) operator.

Syntax of Structure in C


struct structure_name
   {
       type member1;
       type member2;
       type member3;
   };structure_variables;

The structure variables are the structure objects for accessing the structure members.

What is a Union in C?

Union is a user-defined data type declared with a "union" keyword. It is a collection of elements of different data types. All the elements are stored at the same memory location. Only one member can hold a value at a time in a union. The size of the memory depends on the largest member of the union.

Syntax of Union in C


union union_name {
       type member1;
       type member2;
       type member3;
};union_variables;

Difference Between Structure and Union in C Programming

ParametersStructureUnion
KeywordA structure is declared using the "struct" keywordA union is declared using the "union" keyword
MemoryAll the structure members have a unique memory location.All the members share the same memory location.
ValueStores distinct values for all the membersStores same values for all the members
SizeThe sum of the sizes of all the members of a structureThe size of the largest member of the union
Initialization of member variablesMultiple members can be initialized at the same timeOnly one member can be initialized at a time
Accessing MembersYou can access individual members at a timeYou can access only one member at a time
Data typesIt's used for storing various data typesIt's used to store one of the many available data types.
Altering valuesChange in the value of any member does not affect other member's valueChange in the value of one member will affect the value of other members in the union.

Difference Between Structure and Union with Example


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

// Define a structure
struct ExampleStruct {
    int intVar;
    float floatVar;
    char str[20];
};

// Define a union
union ExampleUnion {
    int intVar;
    float floatVar;
    char str[20];
};

int main() {
    // Declare and initialize a structure
    struct ExampleStruct s;
    s.intVar = 42;
    s.floatVar = 3.14;
    strcpy(s.str, "Hello, World!");

    // Declare and initialize a union
    union ExampleUnion u;
    u.intVar = 42;

    u.floatVar = 3.14;
    strcpy(u.str, "Hello, World!");

    // Print structure values
    printf("Structure values:\n");
    printf("intVar: %d\n", s.intVar);
    printf("floatVar: %.2f\n", s.floatVar);
    printf("str: %s\n", s.str);

    // Print union values
    printf("\nUnion values (after setting str):\n");
    printf("intVar: %d\n", u.intVar);   
    printf("floatVar: %.2f\n", u.floatVar);
    printf("str: %s\n", u.str);

    return 0;
}   

Output

Structure values:
intVar: 42
floatVar: 3.14
str: Hello, World!

Union values (after setting str):
intVar: 1819043144
floatVar: 1143139122437582505939828736.00
str: Hello, World!  

In the union declared above, after setting the string value, the intVar and floatVar contain garbage values or may be undefined because they share the same memory location with str.

Related Differences:

Summary
We saw what structures and unions are in the C language, compared them, and saw the differences between them. Both are user-defined data types with multiple applications. You must decide according to your project's requirements to choose the appropriate data structure. For an in-depth understanding, consider enrolling in our C Programming Course.
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification TrainingSep 15SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingSep 15SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
.NET Solution Architect Certification TrainingSep 22SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Software Architecture and Design TrainingSep 22SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingSep 29SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
ASP.NET Core Certification TrainingSep 29SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this