Printing an enum sounds trivial, but every language handles it differently. In C and C++, an enum is just an integer, so printing it directly shows a number, not the name. In Java and Python, enums are objects, so you get the name by default. This guide covers the idiomatic way to print enum names and values in all four languages, plus how to handle custom formatting.
What You’ll Need
- A text editor or IDE (VS Code, IntelliJ, etc.)
- A compiler or interpreter for your language (GCC, G++, JDK, Python 3)
- Basic understanding of enums in your chosen language
Step-by-Step
C (C99 or later)
- Define an enum. For example:
enum Color { RED, GREEN, BLUE }; - To print the name, you need a lookup table. Create an array of strings matching the enum order:
const char* color_names[] = {"RED", "GREEN", "BLUE"}; - Print using the enum as an index:
printf("%s\n", color_names[RED]);This printsRED. - To print the numeric value, cast to int:
printf("%d\n", RED);prints0. - If your enum has custom values, ensure the array matches the actual values. For example,
enum Color { RED=10, GREEN=20 }would need a sparse array or a switch statement.
C++ (C++11 or later)
- Define an enum class:
enum class Color { RED, GREEN, BLUE }; - Printing directly gives an error because enum class doesn’t implicitly convert to int. Use
static_castto print the number.(Color::RED) - For the name, create a function that returns a string based on the enum value. For example:
const char* color_name(Color c) { switch(c) { case Color::RED: return "RED"; case Color::GREEN: return "GREEN"; case Color::BLUE: return "BLUE"; default: return "UNKNOWN"; } } - Print with:
std::cout << color_name(Color::RED) << std::endl; - For C++17, you can use
if constexprwith magic_enum library, but that requires an external library. The switch is simplest.
Java
- Define an enum:
enum Color { RED, GREEN, BLUE } - Print the name using
System.out.println(Color.RED);This callstoString(), which returns the name by default. - To print the ordinal (position), use
Color.RED.ordinal(). - To print a custom label, add a field and constructor to the enum. For example:
enum Color { RED("Red"), GREEN("Green"), BLUE("Blue"); private final String label; Color(String label) { this.label = label; } public String getLabel() { return label; } }Then print
Color.RED.getLabel().
Python
- Define an enum using the
enummodule:from enum import Enumthenclass Color(Enum): RED = 1; GREEN = 2; BLUE = 3 - Print the name using
print(Color.RED.name)which outputs'RED'. - Print the value using
print(Color.RED.value)which outputs1. - Print the whole enum member with
print(Color.RED)which showsColor.RED. - To print a custom string, override
__str__in your enum class.
Common Mistakes
- In C/C++: Trying to print an enum directly with
printforcoutexpecting the name – you get a number or a compile error. - In C: Forgetting that enum values are not necessarily contiguous if you assign custom numbers, leading to out-of-bounds array access.
- In C++: Using
enuminstead ofenum classand then accidentally converting to int implicitly. - In Java: Assuming
ordinal()is stable – it changes if you reorder the enum constants. - In Python: Using
str(Color.RED)expecting the name, but gettingColor.RED– you need.name.
Tips
- In C, use a macro to generate the lookup table and enum together to avoid duplication.
- In C++, consider using a
std::map<Color, std::string>for easy lookup. - In Java, always override
toString()if you need a user-friendly label; don’t rely on the default name. - In Python, use
IntEnumif you need the enum to behave like an integer in comparisons. - For debugging, many IDEs show the enum name in the debugger, but printing to console still needs explicit code.
Troubleshooting
- Printing a number instead of a name in C: You forgot the lookup table. Check that the array index matches the enum value.
- Compile error in C++ when printing enum class: You need to cast to int or provide a conversion function. Use
static_cast<int>. - Java prints something like
Color@1a2b3c: You defined your owntoString()incorrectly or are printing an object reference. Use.name()or.toString()properly. - Python prints
Color.REDinstead ofRED: Use.nameattribute, notstr(). - Enum values are not sequential in C: Use a switch statement or a dictionary/map instead of an array.
Frequently Asked Questions
- Can I print an enum as a string in C without a lookup table? No, C has no reflection. You must manually map names to values.
- Does Java’s
Enum.toString()always return the name? Yes, unless you override it. The default implementation returns the constant name. - In Python, what’s the difference between
nameandvalue?nameis the constant name (e.g., ‘RED’),valueis the assigned value (e.g., 1). - Can I print all enum values at once? Yes:
- C: Loop over the array of names.
- C++: Use a range-based for loop over a vector of enum values.
- Java: Use
Color.values()and loop. - Python: Iterate over
Colorclass directly.
- How do I print an enum value as a number in Java? Use
ordinal()or a custom field that holds the numeric value. - Is there a way to print the enum name in C++ without writing a switch? You can use a macro or a third-party library like magic_enum, but the switch is the most portable.
Related
- What Is enum in Java? Definition & Usage
- How to Update a Dictionary in Python
- Value Dollar Shop Jurong East: Location, Prices & What to Expect
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Not Moving From Cell to Cell? Fixes That WorkIf Excel is not moving from cell to cell when you press the arrow keys, turn off Scroll…
- How to Manually Archive Emails in Microsoft OutlookTo manually archive an email in Outlook, select the message and choose Archive; Outlook moves it to the…
- Excel Data Validation Disabled? Causes and FixesNo—Data Validation is a standard Excel feature, not a setting that is normally switched off for everyone. If…
- Construction Project Timeline Template Excel: Build OneA construction project timeline template in Excel is a task schedule with planned start and finish dates, durations,…
- How to Open Excel in Edge and Use Excel for the WebTo open Excel in Microsoft Edge, go to microsoft365.com, sign in with a Microsoft account, and choose Excel.…
- Excel Reference Table in a Dropdown ListYes. In Excel for Microsoft 365 on Windows, turn the source data into an Excel Table, create a…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.