Union and Typedef in C
Title
Question
What is union?
Which keyword is used to declare union?
How to typedef is used?
What is the main difference between structure and union?
Write a program to display student information(rollno,name,age) using union.
Advance-C Union-and-Typedef 0-1 min 0-10 sec
Answers:
"A union is a special user-defined data type that lets you store different types of data in the same memory location."
unionkeyword is used to declared union.
<code data-end="31" data-start="22">typedef</code> is used to create a new name (alias) for an existing data type. It helps make code simpler, shorter, and easier to read.
Structurestores memory Separate for each member and union shared among all members.
#include <stdio.h>
#include <string.h>
union Student {
int rollno;
char name[20];
int age;
};
int main() {
union Student s;
// Assign and display roll number
s.rollno = 101;
printf("Roll No: %d\n", s.rollno);
// Assign and display name
strcpy(s.name, "Rahul");
printf("Name: %s\n", s.name);
// Assign and display age
s.age = 20;
printf("Age: %d\n", s.age);
return 0;
}

Login to add comment