Open In App

How to Use typedef for a Union in C?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C program to create typedef for union
#include <stdio.h>
  
// Defining a union named MyUnion with three members
union MyUnion {
    int integer;
    float floating_point;
    char character;
};
  
// Creating a typedef for the union
typedef union MyUnion MyUnion;
  
int main()
{
    MyUnion data; // Declaring a variable of type MyUnion
  
    // Assigning printing the values to the member of the
    // union
    data.integer = 100;
    data.floating_point = 5.14;
    data.character = 'A';
  
    // printing the values to the member of the union
    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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads