C also allows users to have a structure within a union. The program given below illustrates the use of structures within a union. There are two structure variables in the union. The size of the union will be size of structure variable which is larger of the two.
STRUCTURES
INSIDE UNIONS
C
also allows users to have a structure within a union. The program given below
illustrates the use of structures within a union. There are two structure
variables in the union. The size of the union will be size of structure
variable which is larger of the two. During run-time, programmer will choose to
enter name or roll number of the student and the corresponding action will thus
be taken.
#include <stdio.h>
typedef struct a
{ int marks;
char name [20];
};
typedef struct b
{ int marks;
int roll_no;
};
typedef union Student
{ struct a A;
struct b B;
};
main()
{
union Student s;
char ch;
printf("\n Do you want to
enter name or roll number of the student : (N/R) - ");
scanf("%c", &ch);
if (ch == 'R')
{
printf("\n Enter the roll
number : ");
scanf("%d", &s. B.
roll_no);
printf("\n Enter the marks:
");
scanf("%d", &s. B.
marks);
}
else
{
printf("\n Enter the name:
");
gets (s.A.name);
printf("\n Enter the marks:
");
scanf("%d",
&s.A.marks);
}
printf("\n ****** STUDENT'S
DETAILS *******") ;
if (ch == 'N')
{
printf("\n NAME: ");
puts (s.A.name);
printf("\n MARKS: %d",
s.A.marks);
}
else
{
printf("\n ROLL NO : %d",
s.B. roll_ no);
printf("\n MARKS : %d",
s.B.marks);
}
}
Output
Do you want to enter name or roll
number of the student : (N/R) – R
Enter the roll number : 12
Enter the marks : 99
****** STUDENT'S DETAILS *******
ROLL NO: 12
MARKS: 99
Programming in C: Unit IV: Structures and Union : Tag: : with Example C Program - Structures Inside Unions
Programming in C
CS3251 2nd Semester CSE Dept 2021 | Regulation | 2nd Semester CSE Dept 2021 Regulation