Thursday, January 16, 2025
HomeProgrammingWhat is C Unions

What is C Unions

In C, a union is a special data structure that allows storing different data types in the same memory location. Unlike a structure, where each member has its own memory space, all members of a union share the same memory. This allows a union to store one value at a time, reducing memory usage.

See also  What are Bitwise Operators in Java?

Syntax:

union UnionName {
dataType member1;
dataType member2;

};

Example:

#include <stdio.h>

union Data {
int i;
float f;
char c;
};

int main() {
union Data data;
data.i = 10;
printf(“%d\n”, data.i); // Prints 10
data.f = 3.14;
printf(“%f\n”, data.f); // Prints 3.14
return 0;
}

See also  How do I completely uninstall Node.js, and reinstall

In the above example, data can hold an int, float, or char, but only one at a time. Unions are useful for memory-efficient applications, especially in embedded systems.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x