0
0
CHow-ToBeginner · 3 min read

How to Use Enum in C: Syntax, Example, and Tips

In C, use enum to define a set of named integer constants for better code readability. Declare it with enum Name {CONST1, CONST2, ...}; and use the names as integer values in your code.
📐

Syntax

An enum defines a list of named integer constants. The syntax is:

  • enum Name {CONST1, CONST2, ...}; declares an enum type named Name.
  • Each constant like CONST1 is assigned an integer value starting from 0 by default.
  • You can assign specific integer values to constants if needed.
c
enum Color {
    RED,    // 0
    GREEN,  // 1
    BLUE    // 2
};
💻

Example

This example shows how to declare an enum and use its values in a program to print a color name.

c
#include <stdio.h>

enum Color {
    RED,    // 0
    GREEN,  // 1
    BLUE    // 2
};

int main() {
    enum Color favorite = GREEN;

    if (favorite == RED) {
        printf("Favorite color is Red\n");
    } else if (favorite == GREEN) {
        printf("Favorite color is Green\n");
    } else if (favorite == BLUE) {
        printf("Favorite color is Blue\n");
    } else {
        printf("Unknown color\n");
    }

    return 0;
}
Output
Favorite color is Green
⚠️

Common Pitfalls

Common mistakes when using enums include:

  • Not specifying the enum type when declaring variables (use enum Name or typedef).
  • Assuming enum constants are strings instead of integers.
  • Assigning values outside the enum range without care.
  • Forgetting that enum constants share the same namespace.
c
/* Wrong: missing enum keyword */
// Color favorite = RED; // Error: 'Color' is not a type

/* Right: use enum keyword or typedef */
enum Color favorite = RED;

/* Or with typedef */
typedef enum {RED, GREEN, BLUE} Color;
Color favorite2 = BLUE;
📊

Quick Reference

ConceptDescription
enum Name {CONST1, CONST2};Declare an enum type with named constants
enum Name var;Declare a variable of enum type
CONST1, CONST2Constants are integer values starting at 0 by default
Assign valuesYou can assign specific integer values to constants
typedef enum {...} Name;Create a type alias for easier use

Key Takeaways

Use enum to create named integer constants for clearer code.
Enum constants start at 0 by default but can be assigned specific values.
Declare variables with enum Name or use typedef for simpler syntax.
Enum constants are integers, not strings, so compare them as numbers.
Avoid name conflicts since enum constants share the same namespace.