C Enums Tutorial

Enums in C are used to define named integer constants. Using enums improves the readability of the code and makes it more maintainable by providing meaningful names to numbers. This tutorial will help you understand the syntax and usage of enums in C programming.

1. Defining an Enum

In C, an enum is defined using the enum keyword, followed by the name of the enum and its values:

enum Weekday {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
};

In this example, the values of the weekdays are automatically assigned integer values starting from 0. Sunday will be 0, Monday will be 1, and so on.

2. Assigning Specific Values

Enums allow you to assign specific values to their constants:

enum Weekday {
    Sunday = 1,
    Monday = 2,
    Tuesday = 3,
    Wednesday = 4,
    Thursday = 5,
    Friday = 6,
    Saturday = 7
};

Here, the values of the days are manually set from 1 to 7.

3. Using Enums in Code

Enums can be used like regular integers. They improve code readability by replacing numeric constants with meaningful names:

#include <stdio.h>

enum Weekday { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main() {
    enum Weekday today = Monday;
    printf("Today is day number %d\\n", today);
    return 0;
}

In the above code, today is an enum variable of type Weekday. The value of today is set to Monday, which will be 1 since the default starting value of Sunday is 0.

4. Enum with Multiple Values

Enums can also hold multiple values by specifying them individually, which is useful when working with flags or options:

enum Permissions {
    READ = 1,
    WRITE = 2,
    EXECUTE = 4
};

int main() {
    enum Permissions userPermission = READ | WRITE;
    printf("User has permission code: %d\\n", userPermission);
    return 0;
}

Here, READ, WRITE, and EXECUTE are combined using bitwise OR (|) to assign a combination of permissions to a variable.

5. Conclusion

Enums are a powerful tool in C that improve code readability, making it easier to understand and maintain. By using meaningful names instead of raw numbers, enums allow for cleaner and more organized code.

0 Interaction
1.1K Views
Views
28 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home