When To Use Enum Instead Of Define In C

  • Enums, which are user-defined data types made up of named constants, are also known as enumerations .
  • They give names a means of being associated with integral values, which improves the readability and maintainability of the code.
  • Type mismatches can be detected by the compiler during compilation because enums are type-safe.
  • Since they employ symbolic names rather than just raw numeric values, they provide improved debugging support.
  • Enums come in particularly useful when we need to define a set of related constant values, like the days of the week, error codes, or menu items.
  • #Define:

    When is it better to use Enum in C instead of Define?

    1. To Display a Collection of States or Options as Integers:

  • When a variable has a limited number of possible states or options, enums are frequently used.
  • For instance, symbolizing the months of a year or the days of a week.
  • Example:

    Example
    
    #include <stdio.h>
    
    // Using enum to represent days of a week with custom values
    enum CustomDayOfWeek {
        CUSTOM_MONDAY = 10,
        CUSTOM_TUESDAY = 20,
        CUSTOM_WEDNESDAY = 30,
        CUSTOM_THURSDAY = 40,
        CUSTOM_FRIDAY = 50,
        CUSTOM_SATURDAY = 60,
        CUSTOM_SUNDAY = 70
    };
    
    int main()
    {
        enum CustomDayOfWeek customDayOfWeek = CUSTOM_WEDNESDAY;
        if (customDayOfWeek == CUSTOM_WEDNESDAY)
            printf("It's a custom Wednesday.\n");
        return 0;
    }
    

Output:

Output

It's a custom Wednesday.

2. Represent Error Codes:

Enums offer a more descriptive approach for defining error codes compared to numeric error codes set with #define macros.

Example

#include <stdio.h>
// Using enum to represent custom error codes
enum CustomErrorCode {
    CUSTOM_ERROR_FILE_NOT_FOUND = 100,
    CUSTOM_ERROR_PERMISSION_DENIED,
    CUSTOM_ERROR_DISK_FULL
};

int main()
{
    enum CustomErrorCode customErrorCode = CUSTOM_ERROR_FILE_NOT_FOUND;
    if (customErrorCode == CUSTOM_ERROR_FILE_NOT_FOUND)
        printf("File not found error.\n");
    return 0;
}

Output:

Output

File not found error.

3. Boosting Type Safety:

We utilize enums within our software to enhance type safety, preventing variables from mistakenly accepting incorrect values. When attempting to assign a value not listed in the enumeration, the compiler will generate an error to notify the developer.

Example

#include <stdio.h>

// Define an enum for different geometric shapes
enum GeometricShape { TRIANGLE, PENTAGON, HEXAGON };

// Define a structure for a shape
struct Shape {
    enum GeometricShape type;
    double sideLength;
    double apothem; // For shapes like polygons
};

// Function to calculate the area of a shape
double calculateArea(struct Shape shape)
{
    switch (shape.type) {
    case TRIANGLE:
        return 0.5 * shape.sideLength * shape.apothem;
    case PENTAGON:
        return 0.5 * shape.sideLength * 5 * shape.apothem;
    case HEXAGON:
        return 1.5 * shape.sideLength * shape.apothem;
    default:
        return 0.0; // Invalid shape
    }
}

int main()
{
    // Create instances of different geometric shapes
    struct Shape triangle = { TRIANGLE, 4.0, 3.0 };
    struct Shape pentagon = { PENTAGON, 5.0, 4.0 };
    struct Shape hexagon = { HEXAGON, 6.0, 5.0 };

    // Calculate and print the areas of the shapes
    printf("Area of triangle: %.2f\n", calculateArea(triangle));
    printf("Area of pentagon: %.2f\n", calculateArea(pentagon));
    printf("Area of hexagon: %.2f\n", calculateArea(hexagon));

    return 0;
}

Output:

Output

Area of triangle: 6.00
Area of pentagon: 50.00
Area of hexagon: 45.00

4. Switch statements:

In order to manage different scenarios based on the enum value, switch statements are also employed with enums. This enhances the readability and maintainability of the code for developers.

Example

#include <stdio.h>

enum ArithmeticOperation { POWER, MODULUS, EXPONENT };

int performArithmeticOperation(int base, int exponent, enum ArithmeticOperation op)
{
    int result;
    switch (op) {
    case POWER:
        result = 1;
        for (int i = 0; i < exponent; ++i) {
            result *= base;
        }
        break;
    case MODULUS:
        result = base % exponent;
        break;
    case EXPONENT:
        result = 1;
        for (int i = 0; i < exponent; ++i) {
            result *= base;
        }
        break;
    default:
        printf("Error: Invalid arithmetic operation!\n");
        return 0;
    }
    return result;
}

int main()
{
    int base = 2, exponent = 3;
    enum ArithmeticOperation op = POWER;

    int result = performArithmeticOperation(base, exponent, op);
    printf("%d %c %d = %d\n", base,
           (op == POWER) ? '^'
                         : (op == MODULUS) ? '%'
                                           : (op == EXPONENT) ? '^' : '/',
           exponent, result);

    return 0;
}

Output:

Output

2 ^ 3 = 8

Input Required

This code uses input(). Please provide values below: