This blog is under construction

Saturday, 19 May 2012

Union definition in C

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 {
          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(, 100, stdin);
        printf("Output:\nName: %s",;
        return 0;

  jp@jp-VirtualBox:~$ ./a.out
  Enter your name:James Darson
  Name: James Darson

No comments:

Post a Comment