Enums in Switch Statements
Part of the Logic & Flow section of Coddy's C journey — lesson 57 of 63.
One of the most powerful combinations in C programming is using enum values with switch statements. This pairing creates exceptionally readable and maintainable control flow logic that clearly expresses your program's decision-making process.
When you use enum constants as cases in a switch statement, the code becomes self-documenting. Instead of seeing mysterious numbers like case 0: or case 5:, you see meaningful names that immediately convey their purpose:
switch (day) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
printf("It's a weekday\n");
break;
case SATURDAY:
case SUNDAY:
printf("It's a weekend\n");
break;
}This approach makes your code much easier to understand and modify. Anyone reading this code immediately knows what each case represents, and adding new cases or changing the logic becomes straightforward. The compiler also helps catch errors - if you misspell an enum constant, you'll get a compilation error rather than a silent bug.
Challenge
EasyCreate a C program that uses an enum with a switch statement to build a simple weather advisory system. Your program should:
- Define an
enumnamedWeatherConditionwith the following constants in this exact order:SUNNYCLOUDYRAINYSTORMYSNOWY
- Write a function named
getWeatherAdvicethat:- Takes an
enum WeatherConditionparameter namedweather - Returns nothing (void)
- Uses a
switchstatement to print weather-specific advice based on the condition:- For
SUNNY: printPerfect day for outdoor activities! - For
CLOUDY: printGood day for a walk, no sun protection needed. - For
RAINY: printDon't forget your umbrella! - For
STORMY: printStay indoors and avoid travel. - For
SNOWY: printDrive carefully and dress warmly.
- For
- Takes an
- Write a function named
getActivitySuggestionthat:- Takes an
enum WeatherConditionparameter namedweather - Returns nothing (void)
- Uses a
switchstatement to suggest activities based on the weather:- For
SUNNY: printSuggested activity: Beach or hiking - For
CLOUDY: printSuggested activity: Photography or gardening - For
RAINY: printSuggested activity: Reading or indoor games - For
STORMY: printSuggested activity: Movie marathon - For
SNOWY: printSuggested activity: Skiing or hot cocoa
- For
- Takes an
- In the main function:
- Declare a variable of type
enum WeatherConditionnamedcurrentWeather - Read an integer from input representing the weather condition (0, 1, 2, 3, or 4)
- Assign the corresponding enum value to
currentWeatherbased on the input - Print the current weather condition in this exact format:
Current weather: [numeric_value] - Call the
getWeatherAdvicefunction withcurrentWeather - Call the
getActivitySuggestionfunction withcurrentWeather
- Declare a variable of type
This challenge demonstrates the power of combining enums with switch statements to create readable, maintainable code. Instead of using confusing numeric cases in your switch statements, you'll use meaningful enum constants that clearly express the program's logic. The switch statement becomes self-documenting, making it easy to understand what each case represents and modify the behavior as needed.
Cheat sheet
Using enum values with switch statements creates readable and maintainable control flow logic:
switch (day) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
printf("It's a weekday\n");
break;
case SATURDAY:
case SUNDAY:
printf("It's a weekend\n");
break;
}This approach makes code self-documenting by using meaningful names instead of mysterious numbers like case 0: or case 5:. The compiler helps catch errors by generating compilation errors for misspelled enum constants rather than silent bugs.
Try it yourself
#include <stdio.h>
// TODO: Define the WeatherCondition enum here
// TODO: Implement the getWeatherAdvice function here
// TODO: Implement the getActivitySuggestion function here
int main() {
// Read input
int weatherInput;
scanf("%d", &weatherInput);
// TODO: Declare currentWeather variable and assign enum value based on input
// TODO: Print current weather condition in format "Current weather: [numeric_value]"
// TODO: Call getWeatherAdvice function
// TODO: Call getActivitySuggestion function
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