enum in c | Enumerated Data Type

enum in c which is enumerated data type gives you an opportunity to invent your own data type and define what values the variable of this data type can take. This can help in making the program listings more readable, which can be an advantage when a program gets complicated or when more than one programmer would be working on it. Using enumerated data type can also help you reduce programming errors

Syntax of enum in c

enum mar_status
{
single, married, divorced, widowed
} ;
enum mar_status person1, person2 ;

Like structures, this declaration has two parts:

  • The first part declares the data type and specifies its possible values. These values are called ‘enumerators’.
  • The second part declares variables of this data type.

Now we can give values to these variables:

person1 = married ;
person2 = divorced ;

This way of assigning numbers can be overridden by the programmer by initializing the enumerators to different integer values

enum mar_status
{
single = 100, married = 200, divorced = 300, widowed = 400
} ;
enum mar_status person1, person2 ;

Uses of Enumerated Data Type

Enumerated variables are usually used to clarify the operation of a program. For example, if we need to use employee departments in a payroll program, it makes the listing easier to read if we use values like Assembly, Manufacturing, Accounts rather than the integer values 0, 1, 2, etc.

Example of enum

# include <stdio.h>
# include <string.h>
int main( )
{
enum emp_dept 
{
assembly, manufacturing, accounts, stores
} ;
struct employee
{
char name[ 30 ] ;
int age ;
float bs ;
enum emp_dept department ;
} ;
struct employee e ;

strcpy ( e.name, "Lothar Mattheus" ) ;
e.age = 28 ; 
e.bs = 5575.50 ;
e.department = manufacturing ;
printf ( "Name = %s\n", e.name ) ;
printf ( "Age = %d\n", e.age ) ;
printf ( "Basic salary = %f\n", e.bs ) ;
printf ( "Dept = %d\n", e.department ) ; 
if ( e.department == accounts )
printf ( "%s is an accounant\n", e.name ) ;
else
printf ( "%s is not an accounant\n", e.name ) ;
return 0 ;
}

Name = Lothar Mattheus
Age = 28
Basic salary = 5575.50
Dept = 1
Lothar Mattheus is not an accountant

Are Enums Necessary ?

Is there a way to achieve what was achieved using Enums in the previous program? Yes, using macros

# include <string.h>
# define ASSEMBLY 0
# define MANUFACTURING 1
# define ACCCOUNTS 2
# define STORES 3
int main( )
{
struct employee
{
char name[ 30 ] ;
int age ;
float bs ;
int department ;
} ;
struct employee e ;
strcpy ( e.name, "Lothar Mattheus" ) ;
e.age = 28 ; 
e.bs = 5575.50 ;
e.department = MANUFACTURING ;
return 0 ;
}

If the same effect—convenience and readability can be achieved using macros then why should we prefer enums ? Because, macros have a global scope, whereas, scope of enum can either be global (if declared outside all functions) or local (if declared inside a function).

Leave a Comment