Differences Between Structures and Unions with Example
In programming languages like C and C++, structures and unions are used to define composite data types, allowing you to group different types of variables together under a single name.
While both structures and unions serve this purpose, they have some key differences in terms of memory allocation and usage.
Structures
Definition:
- A structure is a composite data type that allows you to group variables of different data types under a single name.
- Each member of a structure has its own memory location, and the size of the structure is the sum of the sizes of its individual members.
- You access structure members using the dot (.) operator.
Example:
#include <stdio.h>
// Define a structure named Point
struct Point {
int x;
int y;
};
int main() {
// Declare a variable of type Point
struct Point p1;
// Assign values to the members of the structure
p1.x = 10;
p1.y = 20;
// Access and print the values
printf("Coordinates: (%d, %d)\n", p1.x, p1.y);
return 0;
}
Unions
Definition:
- A union is similar to a structure, but all its members share the same memory location.
- The size of a union is determined by the largest member, and only one member can be accessed at a time.
- Unions are useful when you want to represent a value that could be of different types at different times.
- You access union members using the dot (.) operator, just like with structures.
Example:
#include <stdio.h>
// Define a union named Number
union Number {
int intValue;
float floatValue;
};
int main() {
// Declare a variable of type Number
union Number num;
// Assign values to the members of the union
num.intValue = 42;
// Access and print the value as an integer
printf("Integer value: %d\n", num.intValue);
// Assign a value to the float member and access it
num.floatValue = 3.14;
printf("Float value: %f\n", num.floatValue);
return 0;
}
In the example above, notice that changing the value of one member in the union affects the value of the other member. This is because they share the same memory location. Unions are commonly used when you need to represent a value that can be interpreted in different ways, depending on the context.