简体   繁体   中英

Why does my switch/case default when using enums?

I have the following switch/case statement in Arduino 1.8.7 where the variable led is an integer:

switch (led) {

  case ALL: {
    /* do stuff */
    break;
  }

  case LED1: {
    /* do stuff */
    break;
  }

  case LED2: {
    /* do stuff */
    break;
  }

  case LED3: {
    /* do stuff */
    break;
  }

  case LED4: {
    /* do stuff */
    break;
  }

  default: {
    break;
  }

}

I also have the following enum :

enum LED_References_e
{
  ALL  = 0,
  LED1 = 1,
  LED2 = 2,
  LED3 = 3,
  LED4 = 4
};

When using the enumerated values as cases to the statement, the statement always hits the default clause. If I substitute the enumerated values for the integers that they represent (ie case 0: ... case 1: ... ) then the statement functions as expected.

I have tried, when using the enumerated values within the statement, to reference the enumerator as the value that the switch is performed on:

switch ((LED_References_e)led)

But this also defaults every time.

I am using another enumerator within my program and this functions correctly, however it is conditionally tested using if/else as opposed to switch/case .

My question is twofold:

  1. Why does the switch/case statement seemingly not work with enumerated values?
  2. What fundamental difference am I missing between if/else and switch/case ?

Assuming Max Langhof is correct and there are other names ALL , LED1 , etc... in scope at the switch so that the LED_References_e ones are shadowed, this should help:

I'm not 100% certain about the differences between standard C++ and Arduino C++, but you should be able to do the following:

enum LED_References_e
{
  ALL  = 0,
  LED1 = 1,
  LED2 = 2,
  LED3 = 3,
  LED4 = 4
};

switch (led) {

  case LED_References_e::ALL: {
    /* do stuff */
    break;
  }

  case LED_References_e::LED1: {
    /* do stuff */
    break;
  }

  case LED_References_e::LED2: {
    /* do stuff */
    break;
  }

  case LED_References_e::LED3: {
    /* do stuff */
    break;
  }

  case LED_References_e::LED4: {
    /* do stuff */
    break;
  }

  default: {
    break;
  }

}

What this does is it tells the compiler you explicitly want LED1 ... LED4 from the LED_References_e enum. If there are other LEDx es in the same scope, this should disambiguate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM