Using Switch Statements
From ROBOTC API Guide
General Programming → Programming 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 ); break; case 2: // second button pressed DriveLiftMotor( LIFT_DN_SPEED ); break; default: // either neither or both buttons pressed DriveLiftMotor( 0 ); break; } |
This tip was posted by jpearman over at http://www.vexforum.com/showpost.php?p=221035&postcount=8.