Anonymous Union





















Anonymous Union is used to create and group variables that have something in common. Unlike classes, you would not be able to create objects and use them. Instead you can directly use Anonymous Unions by referring to their elements directly. The variables in the Anonymous Union act like private variables to the Main() function and behave exactly as any other variable defined in their vicinity. The grouping helps us to easily locate the variables that have been linked to a particular purpose. Study the code below and you can easily understand how they work. 

#include <iostream.h>
#include <conio.h>
#include <string.h>

int main()
      {

      clrscr();

      // define anonymous union
            union {
            long l;
            double d;
            char s[4];
            } ;

      // now, reference union elements directly

      l = 100000;
      cout << l << " ";
      d = 123.2342;
      cout << d << " ";
      strcpy(s, "hi");
      cout << s; 
      getch();
      return 0;
}

No comments:

Post a Comment

Custom Search