C++ Conditions

  1. Operators for Conditions

    Here is a list of operators that will be useful when using conditions in C++

    • Equal operator
      Returns true or false if something is equal to something

      int x = 1
      // isOne will be true because x is 1
      bool isOne = x == 1
    • Not equal operator
      Returns true or false if something is not equal to something

      int x = 1
      // isNotOne will be false because x is 1
      bool isNotOne = x != 1
    • Greater than
      Returns true or false if something is greater than something

      int x = 1
      // greaterTen will be false because x is less than 10
      bool greaterTen = x > 10
    • Greater than or equal to
      Returns true or false if something is greater than or equal to something

      int x = 10
      // greaterEqTen will be true because x is 10
      bool greaterEqTen = x >= 10
    • Less than
      Returns true or false if something is less than something

      int x = 1
      // lessTen will be true because x is less than 10
      bool lessTen = x < 10
    • Less than or equal
      Returns true or false if something is less than or equal to something

      int x = 10
      // lessEqTen will be true because x is 10
      bool lessEqTen = x <= 10
  2. If, Else

    if statement checks if value in ( ) is true or false. If its true it evaluates code inside.
    There is also else if that will evaluate code when first condition wasn't true.
    else statement evaluates code when any other if's weren't true.

     int x = 5;
     
     if (x == 5){
         // do some code if x is 5
     }
     else if(x > 5){
         // do some code if x > 5
     }
     else {
         // do some code if x is not 5
     }
  3. Switch

    Switch compares value in ( ) with values given in each case. If there is a match the associated block of code is executed.
    default keyword specifies code to run if there is no case match.
    When C++ reaches a break keyword, it breaks out of the switch block and prevents doing code for rest of the cases.

    int x = 5;
    switch(x){
       case 1:
         // if x == 1 do some code
         break;
       case 2:
         // if x == 2 do some code
         break;
       default:
         // do some code
         break;
    }
  4. Ternary Operator

    Ternary operator is another way to write if/else statements. You write condition and after ? you write what happens if its true and then after : you write what happens if its false

    bool boolean = true;
    int speed = 1;
     
    boolean == true ? speed = 2 : speed = 1;