0

I have an Enum in C like the following:

typedef enum {
    idle,
    backup,
    charge,
} ENUM_LUMI_STATE;

and I have the following function:

ENUM_LUMI_STATE controllerGetState(void) {
    return idle;
}

I want to print it here:

printf("the current status of the system is %s \r\n", controllerGetState());

The resul is Obscure as you can see here:

the current status of the system is þq st

I want to print the current status of the system is "idle". Could you please tell me how?

Sohrab
  • 1,348
  • 4
  • 13
  • 33
  • 2
    Possible duplicate of [How to convert enum names to string in c](https://stackoverflow.com/questions/9907160/how-to-convert-enum-names-to-string-in-c) – Gaurav Pathak Sep 03 '18 at 06:52
  • 2
    Easiest is just to make a look-up table `const char* STR_LUMI_STATE[] = "idle", ....`. Then print `STR_LUMI_STATE[controllerGetState()]`. – Lundin Sep 03 '18 at 06:57
  • 1
    @Gaurav Not really a great dupe, given that things like "X macros" should be the last resort, not the first. A plain string look-up table is sufficient in most cases. – Lundin Sep 03 '18 at 07:01

1 Answers1

1

controllerGetState(void) function returns an enum and not a string. Therefore using %s for the return value will return garbage. You can use a %d to get the value, which will be 0 in this case.

Detailed answer is given in How to convert enum names to string in c

Ravi S
  • 139
  • 3
  • But the OP wants to print a string, so I don't see how this answers the question? – Lundin Sep 03 '18 at 07:34
  • The problem is similar to the one posed in the link I posted in my earlier comment. The solution to print string for an enum is elaborated there. – Ravi S Sep 03 '18 at 07:55