0

in pascal's case statement i can use this:

Var i : integer;  
...  
Case i of   
 1..5 : DoSomething;  
end;

i was wondering if there is a way in can do this with c/c++ in the arduino compiler using:

switch (var) {
   case 1..5:
     // statements
     break;

or is this only possible using if/else?

1

Short answer: No

Longer answer: Each case in a switch statement must be a discrete value (which is why floats and doubles won't work either) but there are way around it. In order of preference:

A) Utilise the "drop through" feature

switch (value)
{ 
  case 1: // Deliberate drop through
  case 2: // Deliberate drop through
  case 3: // Deliberate drop through
  case 4: // Deliberate drop through
  case 5:
    DoThingA();
    break;
  case 6:
    DoThingB();
    break;
}

B) Change the logic so the range is the default (not nice, but if you have no other option):

switch (value)
{ 
  case 6:
    DoThingB();
    break;
  default:
    DoThingA();
    break;
}

C) Use a helper function (Really ugly, but...). There would have to be a good reason not to call the DoThing() from the helper function.

enum DoOptions {EOptionA, EOptionB};
DoOptions DoWhat (int value)
{
  if (value < 6) return EOptionA;
  return EOptionB;
}
switch (DoWhat(value))
{ 
  case EOptionA:
    DoThingA();
    break;
  case EOptionB:
    DoThingB();
    break;
}
  • 1
    I guess ill be using if statements then. thx for the quick reply. – Jelle Bleeker May 31 '18 at 12:14
  • The above posted code results in two(2) compiler messages, 1 warning and 1 error – user3629249 Jun 2 '18 at 17:32
  • That doesn't surprise me, I wrote them to explain what I was trying to say in the text, not to provide a water tight solution to the problem. If you are not able to clear the issues on your own, feel free to post details and I'll solve them for you. – Code Gorilla Jun 4 '18 at 11:47
3

There are some GNU extensions available in the avr-gcc/avr-g++ compilers (used in Arduino IDE for AVR based Arduino boards). One of them is suport of ... for the case:

  switch (i)
  {
    case  10 ... 100:  Serial.println(F("First"));           break;
    case 101 ... 1000: Serial.println(F("Second"));          break;
    default:           Serial.println(F("Everything else")); break; 
  }

But, it's not the part of C/C++ standard, it's just compiler extension, so there is possibility it fails to compile on different platforms (mainly different compiler). So it's better to avoid it in portable code.

  • 1
    In the settings I have turned on extra warnings and I have added the pedantic flag, then the compiler issues a warning: range expressions in switch statements are non-standard. But I still use it anyway. – Jot May 31 '18 at 17:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.