amitchone
amitchone

Reputation: 1638

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 (i.e.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?

Upvotes: 1

Views: 1853

Answers (2)

604
604

Reputation: 1

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

Void led(LED_References_e led) {
  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;

  }
}

Upvotes: -2

Ivan Rubinson
Ivan Rubinson

Reputation: 3339

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 LEDxes in the same scope, this should disambiguate.

Upvotes: 3

Related Questions