Lesson 10 - Comparison Operators

Comparison Operators - The Basics


Comparison operators are present in nearly all if-statements, and they are perhaps some of the most important operators to learn. 


There are a few important operators to use when comparing in if statements:


Operation

Example

Result

Equal To (==)

3 == 4

false

Not Equal To (!=)

3 != 4

true

Greater Than (>)

3 > 4

false

Less Than (<)

3 < 4

true

Greater Than or Equal To (>=)

4 >= 4

true

Less Than or Equal To (<=)

4 <= 4

true



Comparison Operators - VEX Usages


We can use the previous example to show how to detect buttons. In VEX, comparison operators are used to detect button pressing in code. If we wanted to detect the button L1 and bind it to our intake moving, the code would look like this:


pros::Controller controller(CONTROLLER_MASTER);
pros::Motor intake(PORT_NUMBER);

void opcontrol() {
   
    while (true) {
        if(controller.get_digital(DIGITAL_L1) == true){
            intake.move(127);
        }

     
        else{
            intake.move(0);
        }
       
    }
}


NOTE: When using boolean values, you may see some examples being used like this with no operator:

if(controller.get_digital(DIGITAL_L1))

This means the same as setting it equal to true. Whichever way you write it, the if statement will run upon the press of the button.