Tutorial - Understanding Enum in C


Submit solution

Points: 1
Time limit: 10.0s
Memory limit: 64M

Author:
Problem type
Allowed languages
C

Tutorial

Compiled from multiple sources on the internet.

C Enum

Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration.

Syntax:

enum enum_name{const1, const2,  ....... };

By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements during declaration (if necessary).

// Changing default values of enum constants
enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3,
};

Declaration

When you define an enum type, the blueprint for the variable is created.

enum boolean {false, true};
enum boolean check; // declaring an enum variable

Here, a variable check of the type enum boolean is created.

You can also declare enum variables like this.

enum boolean {false, true} check;

Here, the value of false is equal to 0 and the value of true is equal to 1.

Example program using Enum

#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main() {
   printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur, Fri, Sat, Sun);
   printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn, Thurs, Frid, Satu, Sund);
   return 0;
}

Output:

The value of enum week: 10  11  12  13  10  16  17
The default value of enum day: 0    1   2   3   18  11  12

In the above program, two enums are declared as week and day outside the main() function. In the main() function, the values of enum elements are printed.

Why use enums?

An enum variable can take only one value.

Example:

#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card;

int main() 
{
    card = club;
    printf("Size of enum variable = %d bytes", sizeof(card));   
    return 0;
}

Output:

Size of enum variable = 4 bytes

Here, we gett 4 because the size of int is 4 bytes.

This makes enum a good choice to work with flags.

In fact, you can accomplish almost anything in C programming without using enumerations. However, they can be pretty useful in certain situations as shown above.

Now practise the different options possible using Enum in c on HPOJ.


Comments

There are no comments at the moment.