Enumeration or enum in C


In C programming, an enumeration or enum is a user-defined data type that consists of a set of named values. The enum keyword is used to declare an enumeration and to define the set of values it contains.

The basic syntax for declaring an enumeration in C is as follows:

           enumidentifier
           {
                 value1,
                 value2,
                 value3,
                 . . .
           }

Here, the identifier is the name of the enumeration and the value1, value2, value3, etc. are the named values that it contains. Each value is separated by a comma and the list of values is enclosed in curly braces {}.

Here is an example of an enumeration being used in a program:

  • The program starts by including the standard input-output library, stdio.h, which is used to input and output data. .
  • The first enumeration, Bool, is declared with two named values, No and Yes. No is given the value of 10 and Yes is given the value of 20. .
  • In the main function, two variables are declared, a and b, which are of the enumeration types Bool and point respectively. point is another enumeration declared in the program with two named values, x and y. x is given the value of 25 and y is given the value of 26 (as y is not given any value, it takes the value of the previous enumeration + 1, which is 26). .
  • The value of a is set to Yes which is 20 and the value of b is set to y which is 26. .
  • Finally, the values of a and b are printed using the printf function. The program returns 0 to indicate successful execution.

This program demonstrates how to declare and use enumerations in C, how to assign values to enumeration members and how to use enumeration variables in the program.

Source Code

//enumeration or enum in c
 
#include<stdio.h>
enum Bool{No=10,Yes=20};
int main()
{
    enum point {x=25,y};
    enum Bool a;
    enum point b;
    a=Yes;
    b=y;
    printf("\na : %d",a);
    printf("\nb : %d",b);
 
   return 0;
}
 
 
To download raw file Click Here

Output

a : 20
b : 26

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C