Use of typedef in Union

by | Aug 27, 2022 | C

We will use typedef with the union, in the same way we use with structure.

Just we have to replace the keyword ‘struct’ with the keyword ‘union’.

Table of Contents

Program

#include<stdio.h>
#include<string.h>
typedef union student
{
char name[20];
int age;
}st;
int main()
{
printf("Details of the student are as below:\n");


st s1, s2;


strcpy(s1.name,"John");
s1.age=19;
printf("First student\n");
printf("Name: %s\n",s1.name);
printf("Age: %d\n",s1.age);


strcpy(s2.name,"Thomson");
s1.age=21;
printf("Second student\n");
printf("Name: %s\n",s2.name);
printf("Age: %d\n",s2.age);



return 0;
}

 

Output

The code works fine without any error, but the output doesn’t seem to be the desired one because of some limitation union.

The aim of writing the above code is just to make you understand that we can use the typedef keyword in the union too.

 

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.