Open In App

When to Use Enum Instead of Define in C?

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C programming, both #define and enum can be used to declare integer constants but there are situations where using enum is more beneficial than #define. In this article, we will learn when to use an enum instead of define in C.

When to Prefer Enum Instead of Define in C?

Prefer to use Enum over Define in C in the following cases:

1. To Represent a Set of Options or States in the Form of Integers

Enums are commonly used when you have a finite set of options or states that a variable can take. For example, representing the days of a week or months of a year.

Example:

C
// C Program to represent days of a week using enum

#include <stdio.h>

// Using enum to represent days of a week
enum DayOfWeek {
    MONDAY = 1,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
};

int main()
{
    enum DayOfWeek dayOfWeek = WEDNESDAY;
    if (dayOfWeek == WEDNESDAY)
        printf("It's Wednesday.\n");
    return 0;
}

Output
It's Wednesday.

2. Represent Error Codes

Enums are used to define error codes , providing more descriptive error handling compared to numeric error codes defined using #define macros.

Example:

C
// C program to represent error codes using enum

#include <stdio.h>

// Using enum to represent error codes
enum ErrorCode {
    ERROR_INVALID_INPUT = 1,
    ERROR_OUT_OF_MEMORY
};

int main()
{
    enum ErrorCode errorCode = ERROR_INVALID_INPUT;
    if (errorCode == ERROR_INVALID_INPUT)
        printf("Invalid input error.\n");
    return 0;
}

Output
Invalid input error.

3. Improve Type Safety

Enums are used to improve the type safety in our programs. It prevents accidental assignment of invalid values to the variable. The compiler will generate error if you try to assign a value that is not a part of the enumeration.

Example:

C
// C program to use enum to ensure type safety

#include <stdio.h>

// Define an enum for different shapes
enum ShapeType { CIRCLE, SQUARE, RECTANGLE };

// Define a structure for a shape
struct Shape {
    enum ShapeType type;
    double width;
    double height;
};

// Function to calculate the area of a shape
double calculateArea(struct Shape shape)
{
    switch (shape.type) {
    case CIRCLE:
        return 3.14 * shape.width * shape.width / 4;
    case SQUARE:
        return shape.width * shape.width;
    case RECTANGLE:
        return shape.width * shape.height;
    default:
        return 0.0; // Invalid shape
    }
}

int main()
{
    // Create instances of different shapes
    struct Shape circle = { CIRCLE, 5.0, 0.0 };
    struct Shape square = { SQUARE, 4.0, 0.0 };
    struct Shape rectangle = { RECTANGLE, 6.0, 3.0 };

    // Calculate and print the areas of the shapes
    printf("Area of circle: %.2f\n", calculateArea(circle));
    printf("Area of square: %.2f\n", calculateArea(square));
    printf("Area of rectangle: %.2f\n",
           calculateArea(rectangle));

    return 0;
}

Output
Area of circle: 19.62
Area of square: 16.00
Area of rectangle: 18.00

In the above example, the ShapeType enum ensures type safety by restricting the possible values that the type member of the shape structure can have. This prevents accidental assignment of incorrect shape types and helps the user to catch errors at the compile time rather than the run time.

4. Switch Statements

The enums are also used with switch statements to handle different cases based on the enum value. This makes the code more readable and maintainable for the users.

Example:

C
// C Program to use Enums with the switch statements

#include <stdio.h>

enum Operation { ADD, SUBTRACT, MULTIPLY, DIVIDE };

int performOperation(int a, int b, enum Operation op)
{
    int result;
    switch (op) {
    case ADD:
        result = a + b;
        break;
    case SUBTRACT:
        result = a - b;
        break;
    case MULTIPLY:
        result = a * b;
        break;
    case DIVIDE:
        if (b != 0) {
            result = a / b;
        }
        else {
            printf("Error: Division by zero!\n");
            return 0;
        }
        break;
    default:
        printf("Error: Invalid operation!\n");
        return 0;
    }
    return result;
}

int main()
{
    int a = 10, b = 5;
    enum Operation op = ADD;

    int result = performOperation(a, b, op);
    printf("%d %c %d = %d\n", a,
           (op == ADD) ? '+'
                       : (op == SUBTRACT)
                             ? '-'
                             : (op == MULTIPLY) ? '*' : '/',
           b, result);

    return 0;
}

Output
10 + 5 = 15


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads