Difficulty: Easy
Correct Answer: No built-in way; create a mapping (e.g., array of strings) or a switch.
Explanation:
Introduction / Context:
Enums are integers at runtime. This question examines whether C provides a standard mechanism to obtain the symbolic names of enum constants as strings when printing or logging.
Given Data / Assumptions:
Concept / Approach:
The C standard does not retain identifier names for runtime reflection. Enums decay to integral values; there is no standard function to map an enum value back to its identifier name. Programmers typically implement a manual mapping, such as a string array aligned with enum values or a switch statement that returns the corresponding string.
Step-by-Step Solution:
1) Define enum: `enum Color { RED, GREEN, BLUE };` 2) Create mapping: `const char* names[] = { "RED", "GREEN", "BLUE" };` 3) Print by index: `printf("%s", names[value]);` (validate range). 4) Alternatively, write a switch that returns a string literal for each case.
Verification / Alternative check:
Trying to print with `%s` on an enum without a mapping fails; the compiler does not know names at runtime.
Why Other Options Are Wrong:
Option B/C/D/E: No such standard feature or flag exists; sizeof gives size, not names, and build mode does not add reflection.
Common Pitfalls:
Forgetting to keep mapping in sync; relying on non-portable compiler extensions; not handling unknown values safely.
Final Answer:
No—provide your own mapping such as an array of strings or a switch.
Discussion & Comments