C/Arduino switch case

10,608

Solution 1

You will have to use a cascade of if's (also/especially if your value is a floating point number)

int value= ...; 

if (value>=0 && value<=250 {
    // some code 0..250
}
else 
if (value>250 && value<=500) {
    // some code 251..500
}
else 
if (value>500 && value<=1000) {
    // etc.
}
else {
    // all other values (less than zero or 1001...)
} 

Solution 2

switch(val)
{
    case 0 ... 250:
        inRange(val);
        break;

    default:
        outOfRange();
        break;
}

While the code in the previous answer is valid, I would just stick with the switch statement as it is very applicable for the problem to solve.

Please note that using ranges ('...') is not conforming with the ANSI C standard, but it works fine in the Arduino environment.

Share:
10,608
Jo Colina
Author by

Jo Colina

JavaScript lover, JavaScript learner. if(!procrastinator) innovator; if(time){ photographer; designer; }else{ student; exams; }

Updated on June 04, 2022

Comments

  • Jo Colina
    Jo Colina almost 2 years

    I'm writing code on Arduino (very similar to C, which I don't know, or very little), and I have a little issue concerning the switch/case statement.

    I need my Arduino to do this or that depending on the values of a potentiometer (0 to 1023). However, I have no clue how to tell it case "0 to 200". For example, I tried

    case 0..250:
      blablaSomeCode;
      break;
    

    And so on... How can I do it?

    I don't really want to write case 1 case 2 case 3...

  • Jo Colina
    Jo Colina almost 11 years
    Thank's a lot! I actually wrote a function called isIn to verify it! but your code is a lot faster!
  • Nicholaz
    Nicholaz almost 11 years
    Glad to hear! If performance is an issue, you can reorder the ifs in a way that the most common cases are near the top. (And please consider checking the answer as correct.)