Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multi-char literals as enum values

Tags:

c

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',
}
like image 844
fiji3300 Avatar asked Aug 31 '25 03:08

fiji3300


1 Answers

Your proposal is allowed by the C Standard but it may pose problems:

  • compilers might issue warnings about multi-character character constants being implementation defined;
  • the actual values are indeed implementation defined so printing them in an intelligible way is non trivial: (char *)&e might not be a pointer to a null terminated C string with the expected value.
  • it would likely not help with debugging using a debugger as it could display the values as large decimal constants, not as character constants.

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);
}
like image 75
chqrlie Avatar answered Sep 02 '25 15:09

chqrlie