Difference between revisions of "Using switch statements"

Jump to: navigation, search
(Created page with "{{DISPLAYTITLE: Using Switch Statements}} <yambe:breadcrumb self="Using Switch Statements">Programming_Tips_Tricks|Programming Tips Tricks</yambe:breadcrumb> <br /> Here's an...")
(No difference)

Revision as of 20:31, 15 May 2012

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 is an example of a struct. If you have multiple arms on your robot, you can have a struct to hold the properties of each one.

A struct is implemented, and its components are accessed like this:

robotArm leftArm;
leftArm.maxPos = 2000;
leftArm.minPos = 150;
leftArm.armSpeed = 100;

This tip was posted by jpearman over at http://www.vexforum.com/showpost.php?p=221035&postcount=8.