·  C++ – Syntax – Collections – Union

 

- Info:

  - Union is like Struct with exception that all members are saved in the same location.

  - This means that the size of union is equal to the size of the biggest member.

  - This tutorial is based on http://publications.gbdirect.co.uk/c_book/chapter6/unions.html.

 

- Example:

  - This example shows basic struct operations.

  - Create C++ Console Application Test.cpp.

 

    Test.cpp

    #include <stdio.h>

    #include <string.h>

   

    int main() {

   

      // DECLARE UNION PERSON AND CREATE TWO VARIABLES.

      union person{

        int  id;

        char password[10];

      } john, jill;

   

      // CREATE TWO MORE VARIABLES OF UNION PERSON.

      union person jack, lucy;

   

      // SET VALUES OF UNION VARIABLES.

      jack.id = 20;

      strcpy(john.password, "pass");

   

      // GET VALUES OF UNION VARIABLES.

      printf("%i", jack.id      );

      printf("%s", john.password);

   

      // COPY UNION VARIABLE.

      john=jack;

   

      return 1;

   

    }