0

I wanted to know if I could convert the following if else statement into a switch statement in c++. If I can could someone please tell me how, as currently I am getting errors the way I have written it.

This is the if else statement i am trying to convert into a switch statement.

if ( t>=10 && t <=18 ) {
        blue=0; green=1; red=1;
        xb_led=0; xg_led=1; xr_led=1;

    } else if ((t >18 && t<=22)||(t>22 && t<=25)) {
        green=0; blue=1; red=1;
        xg_led=0; xb_led=1; xr_led=1;
    } else {
        red=0; green=1; blue=1;
        xr_led=0; xg_led=1; xb_led=1;
    } 

This is what I have converted it to but I get an error.

switch(t) {

        case t >=10 && t<=18:
        blue=0; green=1; red=1;
        xb_led=0; xg_led=1; xr_led=1;
        break;

        case t >18 && t<=22|| t>22 && t<=25:
        green=0; blue=1; red=1;
        xg_led=0; xb_led=1; xr_led=1;
        break;

        case t >25:
        red=0; green=1; blue=1;
        xr_led=0; xg_led=1; xb_led=1;
        break;             

    }
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
user5647516
  • 1,083
  • 1
  • 9
  • 19

1 Answers1

2

Switch statement cases don't execute based on the label alone. The case label value is compared for equality with the switch value, which in this case doesn't make much sense as we'd have such comparisons as t == (t >=10 && t<=18). For your use case I would stick with the if else.

llllvvuu
  • 286
  • 1
  • 9
  • 1
    *Switch statement cases aren't supposed to be booleans* Why not? – NathanOliver Feb 17 '16 at 14:47
  • What would be the point? There are only two cases. – llllvvuu Feb 17 '16 at 16:19
  • Yes a 2 case switch statement seams silly but that is not the point. When you say *Switch statement cases aren't supposed to be booleans.* that is simply not true. There is no reason why you can't and there may be times you want it like you always want to have the false part run even if the true part runs. Something along the lines of only having to write cleanup code once but have it always executed. – NathanOliver Feb 17 '16 at 17:12
  • In that case fallthough is equivalent to not having an else. I had used the word "supposed" in order to avoid pedantry (because the language obviously allows it), though I can see the educational value in considering for example switching on a constant, and the point wasn't crucial to my answer so I edited it out for clarity. – llllvvuu Feb 17 '16 at 18:48
  • Switch case statements are supposed to resolve to unique values always. That's why typically folks use integers (like error codes which are unique). if you use multiple boolean expressions which could be either true or false, then the compiler will throw an error cause there could be a situation where multiple case statements would both resolve to the same value. The error will occur at compile-time, even though at run-time it may never happen. – TNBtech Apr 17 '16 at 19:39