Introduction
Enums help you give names to numbers. This makes your code easier to read and understand.
Enums help you give names to numbers. This makes your code easier to read and understand.
enum EnumName {
VALUE1,
VALUE2,
VALUE3
};Each name inside enum gets a number starting from 0 by default.
You can assign specific numbers to names if you want.
enum Color {
RED,
GREEN,
BLUE
};enum Day { MONDAY = 1, TUESDAY, WEDNESDAY };
enum Status { SUCCESS = 0, ERROR = -1 };
This program uses an enum to represent traffic light colors. It prints a message based on the current light.
#include <stdio.h> enum TrafficLight { RED, YELLOW, GREEN }; int main() { enum TrafficLight light = RED; if (light == RED) { printf("Stop!\n"); } else if (light == YELLOW) { printf("Get ready...\n"); } else { printf("Go!\n"); } return 0; }
Enums make your code easier to read and maintain.
By default, enum values start at 0 and increase by 1.
You can use enums to improve code safety by avoiding magic numbers.
Enums give names to numbers for better code clarity.
You can assign specific numbers or use default counting.
Use enums to group related constants and avoid errors.
enum in C programming?Color with values RED, GREEN, and BLUE?enum, followed by the name and braces with values separated by commas.enum Color { RED, GREEN, BLUE };. Others use invalid symbols or assignment.enum Day { SUN, MON, TUE = 5, WED, THU };
#include
int main() {
printf("%d %d %d %d %d", SUN, MON, TUE, WED, THU);
return 0;
}enum Status {
OK = 1,
ERROR,
WARNING = "3"
};enum Flags { FLAG_A = 1 << 0, FLAG_B = 1 << 1, FLAG_C = 1 << 2 };
#include
int main() {
int combined = FLAG_A | FLAG_C;
if (combined & FLAG_B) {
printf("Flag B set\n");
} else {
printf("Flag B not set\n");
}
return 0;
}Pass the test and this pattern moves unknown