# Switch - Case

Example:

Switch(hour){

case ((>=6)&&(<=10)):

minTemp = (minTemp +( inc*3));

break;
}

I’d like to avoid writing a long list of cases but I can’t get this to work. Is it possible?

``````case ((>=6)&&(<=10)):
``````

Use ellipses to make a case with a range of values

``````case 6 ... 10: // note space before and after ...
``````

I’d have done it like this, before I read Groundfungus’ post. Now I see there is an alternative way.

``````if ( hour >= 6 && hour <= 10 ) {
minTemp = (minTemp +( inc*3));
}
else if ( hour >= 11 && hour <= 14 ) {
minTemp = (minTemp +( inc*3));
}
else if ( hour >= 15 && hour <= 19 ) {
minTemp = (minTemp +( inc*3));
}
else {
// default
}
``````

What is the result of anything like this:

``````((>=6)&&(<=10))
``````

It will be 0 or 1. This is legal, because it results in a compile time integer, but you will be restricted to 2 cases.

You can use the ellipse notation, but that is a gcc extension, and not standard.

``````case 6:
case 7:
case 8:
case 9:
case 10:
``````

Is the correct, portable way. (Though you can put them all on one line.)

I take the point that it is rubbish but I was in a quandary!!! I am no expert in C++ - did you guess?

How exactly would your suggestion appear on a single line?

I have another problem and I’ll put it in the only way I know how,

``````switch (hour){

case ((>=18 && <=23)||(>=0 && <=5)):

break;

}
``````

It’s gobbledegook I know, but I want an ‘off’ condition between 6pm and 6am.

As pointed out above, I think you need if/else and not switch/case.

But for what you want:

``````switch (hour)
{
case 6: case 7: case 8: case 9: case 10:
// stuff
break;

case 0: case 1: case 2: case 3: case 4: case 5:
case 18: case 19: case 20: case 21: case 22: case 23:
//stuff
break;

default:
// error!
break;
}
``````