Pages

Wednesday, 19 July 2017

Difference Between Union and Enum

Union 


Union is user defined data type which is use to store a data member from more than one data member. Followings are some key point about union
  • Union is also a user defined data type But only one member can be saved at a time
  • A common space allocated for all member
  • Only one member can be initialized at a time.
  • Space allocated equal to higher member allocated space.
  • Only one member value can be read or write at ones.
  • Uses rate is lower than structure due common space allocation.
  • If a member initialized and another attempt for change value of other member lead loss of previous value. 
#include<stdio.h>
union emp
{
     int roll;
     char nm[10];
     char city[10];
};
void main()
{
     union emp ob2;     

     ob2.roll=101;
     printf("\nSize of Union\t %d",sizeof(ob2));
     printf("\nUnion Roll %d",ob2.roll);
     strcpy(ob2.nm,"Girfa");
     printf("\nValue Loss due to Union  %d",ob2.nm); 
}

Enum

Enumerate is user defined data type which is integer value assign to a data member as its options. Enumerate is useful to provide user friendly name for available integer options used as some setting of application. For example if an application has shown available color to its window by integer number as we have seen in dos color command.

So for change color you need to remember color code which increase complexity. By using enumeration you provide color name in user friendly mode.
i.e.  Color.Red,Color.Blue instead of integer code. System will find the correspondence integer related to given color by enumeration definition.


Enumerated types, variables, and typedefs, operate similarly to structs:
     enum color { red, green, blue} formate;
     enum color  ew_bid, ns_bid;

     typedef enum Direction{ NORTH, SOUTH, EAST, WEST } Direction;
     Direction nextMove = NORTH;

Values may be assigned to specific enum value names.

Any names without assigned values will get one higher than the previous entry.
If the first name does not have an assigned value, it gets the value of zero.
It is even legal to assign the same value to more than one name.

Example:
     enum Errors{ NONE=0, // Redundant.  The first one would be zero anyway
          MINOR1=100, MINOR2, MINOR3, // 100, 101, and 102
          MAJOR1=1000, MAJOR2, DIVIDE_BY_ZERO=1000 }; // 1000, 1001, and 1000 again.

Because enumerated data types are integers, they can be used anywhere integers are allowed. One of the best places in in switch statements:
     switch( nextMove ) {
    
          case NORTH:
               y++;
               break;
         
          // etc.
The compiler will allow the use of ordinary integers with enumerated variables, e.g. trump = 2; , but it is bad practice.

enum weekday{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
 
void main()
{
    enum weekday day;
    day = Wed;
    printf("%d",day);
}


No comments:

Post a Comment