This blog is under construction

Saturday, 11 January 2014

Declaration of a union variable in C

Union variable can be declared while defining a union or after defining a union.

Let us see how to declare a union variable while defining a union.
union book {
          char name[32];
          int price;
}obj;

Here, obj is a union variable of type union book and it is declared while defining the union book.

Let us see how to declare a union variable after defining a union.
union book {
          char name[32];
          int price;
};

union book obj1, obj2;

Here, obj1 and obj2 are union variables of type union book.  And they are declared after defining the union book.

Union variable declaration example in C

  #include <stdio.h>
  #include <string.h>
  union book {
        char name[32];
        int price;
  }obj1;  // union variable declaration at definition

  union book obj2;  // union variable declaration after definition

  int main() {
        strcpy(obj1.name, "Davinci code");
        printf("obj1.name: %s\n", obj1.name);
        strcpy(obj2.name, "Twilight");
        printf("obj2.name: %s\n", obj2.name);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  obj1.name: Davinci code
  obj2.name: Twilight




No comments:

Post a Comment