Switch with an integer

void setup() {
// put your setup code here, to run once:

Serial.begin(9600);
}
int k;
void loop() {
k=10;
switch(k){
case((k>=0)&&(k<=5)) Serial.println(“Type : Sur_Longueur”);break;
case((k>=6)&&(k<=10)) Serial.println("Type : Fixe ");break;
case((k>=11)&&(k<=20)) Serial.println(“Type : Sur_Longueur”);break;
case((k>=21)&&(k<=27)) Serial.println(“Type : Fixe”);break;}

}
}

So , i get an error at the 4th case line “case((k>=21)&&(k<=27)) Serial.println(“Type : Fixe”);break;”

Error: the value of ‘k’ is not usable in a constant expression

How to fix this ?
Thanks

I think the test value in each 'case' clause must evaluate to a constant at compile time. Yours include a variable.

Please read this: https://www.arduino.cc/en/Reference/SwitchCase

.

gfvalvo: I think the test value in each 'case' clause must evaluate to a constant at compile time. Yours include a variable.

in each case, i need to check if the value of 'k' is withing that interval of integers or not.

khoubeib: in each case, i need to check if the value of 'k' is withing that interval of integers or not.

Then you'll probably have to do it a different way as I don't think ranges (even constant ones) are supported as the 'case' test conditions.

Actually, it may. Try:

  case const1 ... const2:
    //do stuff
    break;

  case const3 ... const4:
     // do stuff
    break;

Haven't tested it, but it does compile.

gfvalvo: Actually, it may. Try:

  case const1 ... const2:
    //do stuff
    break;

  case const3 ... const4:     // do stuff     break;




Haven't tested it, but it does compile.

Just tried it on an Emulator , it Works, Thanks Bro

if(k<=5)  Serial.println("Type : Sur_Longueur");
else if(k<=10)  Serial.println("Type : Fixe ");
else if(k<=20)    Serial.println("Type : Sur_Longueur");
else if(k<=27)    Serial.println("Type : Fixe");

OR

if(k >=0 && k <=27) {
  switch((k+4) / 5) {
    case 0:
    case 1:
    case 3:
    case 4:
      Serial.println("Type : Sur_Longueur");
      break;
    case 2:
    case 5:
      Serial.println("Type : Fixe ");
      break;
  }
}

OR:

if(k >=0 && k <=27) {
  if(((k+4) / 5) % 3 < 2)
      Serial.println("Type : Sur_Longueur");
  else
      Serial.println("Type : Fixe ");
}

Although that last one might be a little obscure.

khoubeib: Just tried it on an Emulator , it Works

That's not an approach I'd get used to relying on.

Although that last one might be a little obscure

A little? Code is supposed to be easy to understand, like your first example. The others require (varying amounts of) more study, and cause a lot of WTF moments.

KISS still applies.

Just for the record, the "..." is a GCC extension, and might not be portable. You should comment it as such. You also need to be careful with spaces: "2 ... 12" will work "2...12" might not since "2.." is an invalid floating point constant.