fbpx

Understanding Enumerators in C: Simplify Your Code with Enumerators

Understanding Enumerators in C: Simplify Your Code with Enumerators


INTRODUCTION

In programming, enums, or enumerations, introduce a way to make code more readable, efficient, and type-safe. An enum is a user-defined data type that allows you to define a set of named values—known as enumerators—that represent a collection of related constants. Instead of relying on numeric or string constants, which can be error-prone or difficult to interpret, enums let you use descriptive names directly in your code.

For instance, if you want to define the days of the week in C, you can use an enum, allowing you to refer to Mon, Tue, and so forth, rather than remembering numeric codes like 1 for Monday, 2 for Tuesday, and so on. This not only makes the code easier to read but also prevents errors that may arise from incorrectly typing numeric or string constants.

In programming, enumeration (or enum) is a user-defined data type that consists of a set of named values, often called enumerators.

Enums help make code more readable by allowing the use of descriptive names instead of numeric or string constants.

// An example program to demonstrate working

// of enum in C

#include<stdio.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()

{

    enum week day;

    day = Wed;

    printf(“%d”,day);

    return 0;

}

 

Enums help make code more readable by allowing the use of descriptive names instead of numeric or string constants.

How to differentiate the enums with numeric and string constants?

Numeric constants:

———————-

#include <stdio.h>

#define SUNDAY 0

#define MONDAY 1

#define TUESDAY 2

int main() {

    int today = SUNDAY;

    if (today == SUNDAY) {

        printf(“Today is Sunday.\n”);

    }

    return 0;

}

 From the above examples we can change the Integer value at any time as an 8;There is no type safety    in case of integer constants;

 Enum  constants:

#include<stdio.h>

enum week={mon,tue,wed,thu,fri ,sat,sun};

Int main()

{

enum  week day;

day=”mon”;

if(day==”mon”)

{

printf(“today is Sunday”);

}

 

  Whereas in case of enum  there is type safety later on the value of enum cannot be  changed.

String constants:

#include <stdio.h>

#include <string.h>

int main()

{

    const char *signal = “RED”;

    if (strcmp(signal, “RED”) == 0) {

        printf(“Stop!\n”);

    }

    return 0;

}

Enum with strings:

————————

Here, signal is a string constant.

It’s not efficient because string comparisons (strcmp) are slower than integer comparisons,

 and you might make errors (e.g., “Red” vs “RED”).

#include<stdio.h>

Enum traffic={RED,YELLOW,RED}

Int main()

{

enum traffic signal;

signal=RED;

If(signal==RED)

{

printf(“signal is red buses has to stop”);

}