Below is the general form for defining an union. Keyword union is followed by name of the union and the data members of the union are enclosed inside set braces as shown below.
union tag_name {
type data1;
type data2;
------
------
};
Consider the following example,
union student {
union student {
int rollno;
char name[100];
} obj;
union - Keyword
student - name of the union
rollno, name - data members of the union
Example C program to illustrate how to define an union:
#include <stdio.h>
union data {
char name[100];
};
int main() {
union data d1;
printf("Enter your name:");
fgets(d1.name, 100, stdin);
printf("Output:\nName: %s", d1.name);
return 0;
}
Output:
jp@jp-VirtualBox:~$ ./a.out
Enter your name:James Darson
Output:
Name: James Darson
Enter your name:James Darson
Output:
Name: James Darson
No comments:
Post a Comment