selective structure switch and case statements

27 Mar 2011

I've read cplusplus and my own tech notes but the following code wont compile, the errors are Expression must have integral or enum type (E847) basically I'm passing a float value from srf08 to the variable distance and then testing the value of distance. Any advice is really welcome.

int main() {
    float distance;
    while (1) {
        lcd.cls();
        distance = RangeReading();
        lcd.printf("Range: %2.f cm\n",distance);
        // lcd.printf("Temp: %.2f degC\n", temperature.read());
        switch (distance){
        case (>100):
        DriveForwardFullSpeed();
        break;
        case (>80 || <100):
        DriveForwardSlow();
        break;
        case (<50):
        ZeroSpeedForward();
        wait(5);
        break;
        case >20:
        DriveReverse();
        break;
        wait(5);
        ZeroSpeedReverse();
        wait(5);
    }
27 Mar 2011

I think the issue is that a switch statement will only work with a simple integer or equivelant value. It also looks as if you syntax is slightly wrong but fixing that would not solve your problem.

The simple way to make this work would be a series of if statements.

if ( distance > 80 || distance < 100 )
        {
        DriveforwardSlow() ;
        }

One such snippet for each identified different case.

The curly brackets are optional with a single statement to be used but I personally always put them in just I case I ever need to modify the code

Allan

27 Mar 2011

Hi,

The C/C++ syntax is like

switch (value) {
case 0:
case 1:
case ...
case 50: {
          //some code for value 0..50
         }
         break;
}

CC++ lacks the pascal option to use 0..50 as single case selector, minimizing lines a bit.

So it's either above code or use if/then/else statements.

27 Mar 2011

Thanks for that Allan, I'll use a series of If Else statements I've had that working once I was just trying to find a method of reducing my code.

27 Mar 2011

Thanks Wlm, pennies dropped now, I'll have to use If Then Else in my case as I'm testing for the value of what the srf08 is returning and at any instance it would be a value not necessarily equal to the case statement value.

Thanks.

27 Mar 2011

Hi,

Sometimes you can use the default: case of the switch statement if you're lucky (to catch all other values). But in your case that isn't an option too.

But: you could divide distance by 10 (and cast it as an integer) and have a relatively small switch statement if you catch >100 by the default case.

Pro of using a switch statement is code readability.

14 Nov 2017

how do you use a string input to select you case or state