QUESTION 23
What is an enumeration?
2 marksAnswer
An enum declares named integer constants for a related group, such as enum State { IDLE, RUNNING, DONE };.
QUESTION 23
An enum declares named integer constants for a related group, such as enum State { IDLE, RUNNING, DONE };.
QUESTION 24
Enumeration constants give meaningful names to related integer choices or states.
enum State { IDLE, RUNNING = 5, DONE };
enum State state = RUNNING;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.
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.
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.
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.
/* 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;
}The example uses values in the code.
Running