Using Switch Statements

Revision as of 20:31, 15 May 2012 by Bfeher (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
General ProgrammingProgramming Tips Tricks → Using Switch Statements

Here's another tip demonstrating the use of the switch statement.

Let's say you have a motor that you want to drive forward if you press one button and backwards if you press a different button. If you press both or neither buttons the motor should be stopped. You could program this with cascaded if..then..else statements but another way is to combine the two buttons into one variable and use a switch statement. The "<<" is a shift left operator which is often used instead of multiply by 2. DriveLiftMotor would be a function to actually send values to the motor. Everything in capitals are constants defined elsewhere in the code:

// LiftCtl will be 0, 1, 2 or 3 depending on which buttons are pressed
LiftCtl = (vexRT[ LIFT_DN_BUTTON ] << 1) + vexRT[ LIFT_UP_BUTTON ];
switch( LiftCtl )
    case    1:  // first button pressed
        DriveLiftMotor( LIFT_UP_SPEED );
    case    2: // second button pressed
        DriveLiftMotor( LIFT_DN_SPEED );
    default:  // either neither or both buttons pressed
        DriveLiftMotor( 0 );

This tip was posted by jpearman over at