Lesson contents

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

  1. Start with Unit is 3
  2. Do this Multiply by 2
  3. Result 6
Give 3 a name and reuse that name in the multiplication.
lesson.c
#include <stdio.h>

int main(void) {
    const int unit = 3;
    printf("%d\n", 2 * unit);
}
Output
6
Advertisements

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.

Length of a slot: 30 minutes. Rehearsal: 3 slots. Time reserved: 90 minutes.
Reserve a rehearsal room

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
lesson.c
#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;
}
Output
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.

WG14 C language draft (PDF)

Related tags

  • C
  • constants
  • bindings
  • configuration