Home » C Programming » Tutorial » Union
Union in C Programming
The union is a user defined data type in C programming. It can have n numbers of members but only one member can be accessed at one time. The union was invented to prevent memory fragmentation. The union data type prevents fragmentation by creating a standard size for certain data. The members of union can be accessed with . (dot) or -> operators.
Example on union
#include union myunion { float A; int B; }; int main() { union myunion numbers; numbers.A = 7.5; numbers.B = 77; printf("\n Size of : %d", sizeof(numbers)); return 0; }
Typedef with union
#include typedef union myunion { float A; int B; }MYUNION; int main() { MYUNION numbers; numbers.A = 7.5; numbers.B = 77; printf("\n Size of : %d", sizeof(numbers)); return 0; }
Accessing Members of union
#include typedef union myunion { float A; int B; }MYUNION; int main() { MYUNION numbers; numbers.A = 7.5; numbers.B = 77; printf("\n A is : %f", numbers.A); printf("\n B is : %d", numbers.B); return 0; }
One member should be accessed at one time in union
#include typedef union myunion { float A; int B; }MYUNION; int main() { MYUNION numbers; numbers.A = 7.5; printf("\n A is : %f", numbers.A); numbers.B = 77; printf("\n B is : %d", numbers.B); return 0; }
C Tutorial
- History of C Language
- The First Program in C
- Compilation & Execution
- Compile C on Dev-C++
- Compile C on GCC Linux
- Variable & Data types
- Comments
- Storage Classes
- Conidtional Statements
- Switch Cases
- Loops (for, while, do-while)
- Arrays
- Pointers
- Function Pointer
- Strings & Library func
- Formated I/O
- Structure
- Enum
- Union
- File I/O
- Memory Management
- Error Handling
- Type Casting