Structure and Union in C
Here you will get a program code of structure and union in C programming language. It will help you to understanding the difference and the use of structure and union.
Difference between Structure and Union
Structure and Union are both user-defined data types in C programming. The main difference between structure and unions in c is following:-
Structure | Union |
A structure is a grouping of one or more variables with a same name that may be of multiple types. | A union is similar to a structure, but instead of containing multiple variables, all of them share the same memory location. |
Structure and Union in C program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include<stdio.h> #include<conio.h> union contact { char mobileno[10]; char email[15]; }; struct employee { int eid; char name[15]; union contact mode_of_contact; }; int main() { struct employee emp; int mode; printf("Enter employee id and Name :\n"); scanf("%d%s",&emp.eid,emp.name); printf("\nEnter mode of contact :"); printf("\nEnter 1 for mobile no.\n2 for email\n"); scanf("%d",&mode); if(mode==1) { printf("\nEnter Mobile number:"); scanf("%s",emp.mode_of_contact.mobileno); printf("%d\t%s\t%s\n",emp.eid,emp.name,emp.mode_of_contact.mobileno); } else { printf("Enter Email-id:"); scanf("%s",emp.mode_of_contact.email); printf("%d\t%s\t%s\n",emp.eid,emp.name,emp.mode_of_contact.mobileno); } getch( ); } |
Output
Enter employee id and Name :
101 raju
Enter mode of contact :
Enter 1 for mobile no.
2 for email
1
Enter Mobile number:9313654789
101 raju 9313654789
Check out our other C programming Examples