Skip to study material
← Question index

QUESTION 24

Explain enumeration types and their use as named states.

5 marks

Answer in brief

Enumeration constants give meaningful names to related integer choices or states.

Declaration

enum State { IDLE, RUNNING = 5, DONE };
enum State state = RUNNING;

Values

The first constant without an explicit value starts at 0. A later unspecified constant is one more than the preceding value. In this example IDLE is 0, RUNNING is 5 and DONE is 6. Explicit values can represent a chosen external convention when that convention is suitable.

Uses

An enum can name menu choices, a machine state, an operation kind or the tag of a union. The program can use these names in if or switch rather than unexplained numbers. The example’s switch recognises RUNNING and displays a matching message.

Enum versus strings

The constant RUNNING is not the text "RUNNING". Printing its name requires a mapping, such as a switch. In the C11 model used here, enumeration constants have type int. The size of an enum object is not guaranteed to be one byte or identical on every implementation.

Important points

Choose distinct values when distinct cases are required, especially in switch labels. An enum does not automatically check every incoming integer against a permitted state list. Validate external input before treating it as a meaningful state. Using a named state comparison or switch branch adds only fixed work in this small example; the chosen action has its own cost.

Complete C example

main.c

Download main.c
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
enum State { IDLE, RUNNING = 5, DONE };

int main(void)
{
    enum State state = RUNNING;
    switch (state) {
    case IDLE: puts("Idle"); break;
    case RUNNING: puts("Running"); break;
    case DONE: puts("Done"); break;
    default: puts("Unknown"); break;
    }
    return 0;
}

Sample input and output

The example uses values in the code.

Output

Running