To make debugging easier, one could set enum
values to be multi-char literals, which could then be printed. I never saw this being done, and so I'm wondering if there are any reasons why this wouldn't be a good idea?
Here's what I mean:
enum MyEnum {
ME_FOO = 'FOO\0',
ME_BAR = 'BAR\0',
}
Your proposal is allowed by the C Standard but it may pose problems:
(char *)&e
might not be a pointer to a null terminated C string with the expected value.If you define the variables with the proper type enum MyEnum
, the debugger should display the values using the symbolic names (gdb and lldb do this) so the actual values do not matter and keeping them small has other good side effects (efficient dispatch in switch
statements, use as index into arrays...)
For debugging with printf
statements, it is easy to define an array of strings to print enum value names instead of their numeric values:
#include <stdio.h>
enum MyEnum {
ME_FOO,
ME_BAR,
};
static const char * const MyEnum_names[] = {
// using designators to allow for non consecutive values
[ME_FOO] = "FOO",
[ME_BAR] = "BAR",
};
void MyEnum_print(enum MyEnum e) {
unsigned int n = e;
if (n < sizeof(MyEnum_names) / sizeof(MyEnum_names[0]) && MyEnum_names[n])
printf("%s", MyEnum_names[n]);
else
printf("MyEnum(%u)", n);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With