C — Constants with enum and const
An enumeration constant can name an integer constant expression in C. A const-qualified object lets the program express that a stored value is read-only through that name.
A simple example
Use a fixed value
- Start with Unit is 3
- Do this Multiply by 2
- Result 6
#include <stdio.h>
int main(void) {
const int unit = 3;
printf("%d\n", 2 * unit);
}
6
Name a fixed scheduling interval
Express a 30-minute slot in terms of a 15-minute base interval. Keep the slot count separate so different bookings can reuse the same rule. The enum values are available at translation time. In C17, a block-scope const int object generally cannot stand in for an integer constant expression such as a case label.
The music room can be booked in 30-minute slots. A rehearsal needs three slots, so the calendar sets aside 90 minutes. Naming the slot length lets every booking use the same rule.
Run the example
Use a C17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
#include <stdio.h>
int main(void) {
enum { BASE_MINUTES = 15, SLOT_MINUTES = 2 * BASE_MINUTES };
const int slots_booked = 3;
printf("%d minutes\n", slots_booked * SLOT_MINUTES);
return 0;
}
90 minutes
Two base intervals make each slot 30 minutes. A booking of three slots lasts 90 minutes.
Try it yourself
If the base interval changes to 10 minutes, how long is the same three-slot booking?
Check your answer
Each slot now lasts 20 minutes, so the booking lasts 60 minutes.