0
0
C++programming~30 mins

Structure vs union comparison in C++ - Hands-On Comparison

Choose your learning style9 modes available
Structure vs Union Comparison in C++
📖 Scenario: Imagine you are working on a simple device that can store either a temperature reading or a humidity reading, but not both at the same time. You want to see how using a structure and a union affects the memory used by your program.
🎯 Goal: You will create a struct and a union with the same members, assign values, and then print their sizes and stored values to understand the difference between them.
📋 What You'll Learn
Create a struct named SensorDataStruct with two int members: temperature and humidity.
Create a union named SensorDataUnion with the same two int members: temperature and humidity.
Assign values to the members of both the structure and the union.
Print the sizes of the structure and the union using sizeof.
Print the values stored in the structure and the union to observe how they behave.
💡 Why This Matters
🌍 Real World
Structures and unions are used in embedded systems and low-level programming where memory usage is critical, such as sensor data storage or hardware registers.
💼 Career
Understanding the difference between structures and unions helps in writing efficient code for memory-constrained environments and is a common topic in technical interviews for systems programming roles.
Progress0 / 4 steps
1
Create the structure SensorDataStruct
Create a struct named SensorDataStruct with two int members: temperature and humidity. Then declare a variable dataStruct of this type.
C++
Need a hint?

Use the struct keyword to define a structure with two integer members.

2
Create the union SensorDataUnion
Create a union named SensorDataUnion with two int members: temperature and humidity. Then declare a variable dataUnion of this type.
C++
Need a hint?

Use the union keyword to define a union with two integer members.

3
Assign values to the structure and union members
Assign 25 to dataStruct.temperature and 60 to dataStruct.humidity. Then assign 25 to dataUnion.temperature and 60 to dataUnion.humidity.
C++
Need a hint?

Assign values to each member using the dot . operator.

4
Print sizes and values of structure and union
Print the size of SensorDataStruct using sizeof(dataStruct) and the size of SensorDataUnion using sizeof(dataUnion). Then print dataStruct.temperature, dataStruct.humidity, dataUnion.temperature, and dataUnion.humidity to observe the stored values.
C++
Need a hint?

Use std::cout to print the sizes and values. Remember that the union shares memory, so the last assigned value will affect what you see.