C tutorial: Union in C programming language

Programming languages or concepts

  Union in C programming language


         Union in C.

  • Union is a user defined data type.
  • In union all members share the same memory location.
  • The keyboard union is used to define a union.
  • When a variable is associated with the union, the compiler or locate the memory by considering the size of the the largest memory. So size of union is equal to the size of largest memory.
  • Only one member can be accessed at a time.
  • Only 1st members of union can be initialised.

Defining a union:-

  Define a union is a same as we defining a structure.

The keyword union is used to define union.


Syntax:-

      Union [Union Tag]

       {

           Memory definition;

            .............

          }[One or more union Variable];

Union tag is optional.

Ex.

Union Demo {

         int a;

          float mark;

           char name [50] ;

      }data;


The union statement defines a new data type with more than one members for your program.


  Accessing Union members:-

   To accessing any member of the union we can the member access operator ( . ).

the member access operator is coded as a period between the union variable name and the union member that we wish to access.

We would use the keyword Union to define variables of union type.


Syntax:-

         Union test

           {

               int a;

                char c;

            }t;

            t.a;

             t.c;


Ex 

   #include <studio.h>

    Union test {

       int marks;

       char ch ;

         };

           int main ( )

            {

               Union test ts;

                ts.marks = 99;

                ts.ch = 'c';

                printf ("%d \n ", st.marks );

                printf("%d \n ",st.ch);

                return 0;

            }


Pointer to Union:-

   we can have pointers to Union and can access member using the arrow operator (->).

Ex.

  #include<studio.h>

  Union test {

    int mark;

     char ch;

     };

       int main ( )

        {

             Union test ts1;

             ts.mark = 99;

             Union test*ts2 = &ts1;

        printf("%d %c ", ts2 -> mark, ts2 -> ch);

      return 0;

        }


close