enum for Named Constants
Part of the Logic & Flow section of Coddy's C journey — lesson 55 of 63.
When writing C programs, you often need to work with sets of related constant values. For example, you might need to represent days of the week, months of the year, or different states in a program. Instead of using raw numbers like 0, 1, 2, you can use enum to create meaningful names for these constants.
An enumerated type, or enum, allows you to define a group of named integer constants. This makes your code much more readable and easier to maintain. Here's the basic syntax:
enum DayOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};By default, the first name gets the value 0, the second gets 1, and so on. So MONDAY equals 0, TUESDAY equals 1, and SUNDAY equals 6. This approach is much clearer than remembering that day 0 means Monday or day 6 means Sunday.
Using enum makes your code self-documenting and helps prevent errors that can occur when using magic numbers throughout your program.
You can declare variables of enum type and assign enum values to them:
enum DayOfWeek today;
today = MONDAY; // assigns 0 to todayChallenge
EasyCreate a C program that defines an enum for traffic light colors and demonstrates its usage. Your program should:
- Define an
enumnamedTrafficLightwith the following constants in this exact order:REDYELLOWGREEN
- In the main function:
- Declare a variable of type
enum TrafficLightnamedcurrentLight - Read an integer from input representing the traffic light state (0, 1, or 2)
- Assign the corresponding enum value to
currentLightbased on the input:- If input is 0, assign
RED - If input is 1, assign
YELLOW - If input is 2, assign
GREEN
- If input is 0, assign
- Print the current light status in this exact format:
Current light: [enum_name] - Print the numeric value of the current light in this exact format:
Numeric value: [number] - Determine and print the action based on the current light:
- If
RED: printAction: Stop - If
YELLOW: printAction: Caution - If
GREEN: printAction: Go
- If
- Calculate and print the next light in the sequence:
- If current light is
RED(0), next isGREEN(2) - If current light is
YELLOW(1), next isRED(0) - If current light is
GREEN(2), next isYELLOW(1)
- If current light is
- Print the next light in this exact format:
Next light: [enum_name]
- Declare a variable of type
This challenge demonstrates how enum constants make code more readable than using raw numbers. Instead of remembering that 0 means red, 1 means yellow, and 2 means green, you can use meaningful names like RED, YELLOW, and GREEN. You'll practice defining an enum, using enum constants in assignments and comparisons, and accessing the underlying integer values of enum constants.
Cheat sheet
An enum allows you to define a group of named integer constants, making code more readable than using raw numbers:
enum DayOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};By default, the first name gets value 0, the second gets 1, and so on. So MONDAY equals 0, TUESDAY equals 1, etc.
You can declare variables of enum type and assign enum values to them:
enum DayOfWeek today;
today = MONDAY; // assigns 0 to todayTry it yourself
#include <stdio.h>
// TODO: Define the TrafficLight enum here
int main() {
// Read input
int input;
scanf("%d", &input);
// TODO: Declare currentLight variable and assign enum value based on input
// TODO: Print current light status
// TODO: Print numeric value
// TODO: Print action based on current light
// TODO: Calculate and print next light
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters7Structures (structs)
What is a Struct?Declaring a StructCreating Struct VariablesAccessing Struct MembersInitializing StructsRecap: Student Data Struct10Enums and Typedef
enum for Named ConstantsDeclaring and Using EnumsEnums in Switch StatementsUsing typedef for Type Aliasestypedef with StructsRecap: Typedef & Enum Practice2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions