How to Use typedef for a Union in C?
Last Updated :
19 Feb, 2024
In C, typedef is used to give an existing type an alias or a new name. In this article, we will learn how to create a typedef for a union in C.
Use the typedef union in C
We can define a union and create an alias for it using the typedef
keyword which we will be able to use in place of that union name.
Syntax
For defining the union and creating a typedef simultaneously use:
typedef union UnionName {
// Member declaration
} TypedefName;
For defining the union first, then creating a typedef use:
union UnionName {
// Member declaration
};
typedef union UnionName TypedefName;
C Program to Create an Alias Using typedef for a union
The below program demonstrates the use typedef keyword to create a typedef for a union in C.
C
#include <stdio.h>
union MyUnion {
int integer;
float floating_point;
char character;
};
typedef union MyUnion MyUnion;
int main()
{
MyUnion data;
data.integer = 100;
data.floating_point = 5.14;
data.character = 'A' ;
printf ( "Integer value: %d\n" , data.integer);
printf ( "Floating-point value: %.2f\n" ,
data.floating_point);
printf ( "Character value: %c\n" , data.character);
return 0;
}
|
Output
Integer value: 1084521025
Floating-point value: 5.14
Character value: A
Share your thoughts in the comments
Please Login to comment...