Question about switch

Hello, i have to say i'm a total newbie on arduino and try to work on my first project. My project does need a large use of the

switch (var){}

function. Acutally i have 50 "case" to try, each case wil result in a number from -1000 to 1000.

My question is, do i need to write it all the time or is there a better way to solve it?

I'm familiar with php and instead of switch i can do something like this:

$var=array("100","200","300");
echo $var[1]; //prints 100
echo $var[2]; //prints 200

So i don't have to write 50 times "case and break".

Can arduino do something similar? :slight_smile:

Thanks for your help!

Can arduino do something similar?

What you really mean is can C++ do the same ?
Certainly

char * anArray[] = {"100", "200", "300"};

void setup()
{
  Serial.begin(115200);
  Serial.println(anArray[0]);
  Serial.println(anArray[1]);
  Serial.println(anArray[2]);
}

void loop()
{
}

Are the array entries chars or its ?
Either will work in C++ if the array is declared correctly

My entries are integers from -1000 to 1000

Maybe you need (want?) to tell us what it is you're trying to do.

ropol:
My entries are integers from -1000 to 1000

So use int as the variable type for the array. The reason that I asked is that there could be a difference between it printing 100 etc and the entry being "100" etc

This solution worked perfectly! :slight_smile:

Saved me 40 "case,break" :slight_smile:

Thank you very much for this fast solution!

int TMZvalues[] = {0,0,60,120,180,210,240,270,300,330,345,360,390,420,480,510,525,540,570,600,630,660,720,765,780,840,-60,-120,-180,-210,-240,-300,-360,-420,-480,-540,-570,-600,-660,-720};


long TMZ_calculation() {
  long TMZ_offset = TMZvalues[TMZ_eeprom]*60;
  return TMZ_offset;
}

The underlying compiler determines what you can do within the IDE. In this case it is GCC so this construct is also supported:

switch (var) {
    case 1 ... 10:
      //do something when var equals 1 to 10
      break;
    case 20 ... 40:
      //do something when var equals 20 to 40
      break;
    default: 
      // if nothing else matches, do the default
      // default is optional
    break;
  }

For details, consult the GCC reference documentation

In this case it is GCC so this construct is also supported:

It's a shame about the comments, don't you think ?