Monday, 20 March 2017

Program based on Enumeration (or enum) in C


1. Two enum names can have same value. For example, in the following C program both ‘Failed’ and ‘Freezed’ have same value 0.

#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};
 
int main()
{
   printf("%d, %d, %d", Working, Failed, Freezed);
   return 0;
}
 
2. If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1, and so on.
#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
 
int main()
{
    enum day d = thursday;
    printf("The day number stored in d is %d", d);
    return 0;
}
 
3. We can assign values to some name in any order. All unassigned names get value as value of previous name plus one.
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,
          wednesday, thursday = 10, friday, saturday};
 
int main()
{
    printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
            wednesday, thursday, friday, saturday);
    return 0;
}
 
 
 
 

No comments:

Post a Comment