Skip to main content

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




Comments

Popular posts from this blog

restorecrtmode example in c

Header file:     graphics.h Synopsis:        void restorecrtmode();       Description:       restorecrtmode() restores screen mode to text mode. restorecrtmode function in c graphics   #include <graphics.h>   #include <stdlib.h>   #include <stdio.h>   #include <conio.h>   int main(void) {         /* request auto detection */         int gd = DETECT, gmode, err;         int midx, midy;         /* initialize graphics and local variables */         initgraph(&gd, &gmode, "C:/TURBOC3/BGI");         /* read result of initialization */         err = graphresult();         if (err != grOk) {                 /* an error occurred */               ...