Switch

  1. Switch Flow Control
  2. The switch statement allows us to replace several nested if-else constructs and thus improve the readability of our code.

    switch Control Flow Diagram
  3. Syntax :

  4. switch(variable_expression) {
       case constant_expr1: {
           // statements;
       }
       break;
       
       case constant_expr2: {
           //statements;
       }
       break;
       
       default: {
           //statements;
       }
       break;
    }


  5. Example
  6. Let's say, we have the following nested if-else statements:


    import 'dart:io';

     

    void main() {

      print("enter +,-,*,%");

      String oper = stdin.readLineSync();

      int x = 15, y = 7, result;

      if (oper == "+") {

        result = x + y;

      } else if (oper == "-") {

        result = x - y;

      } else if (oper == "*") {

        result = x * y;

      } else if (oper == "%") {

        result = x % y;

      } else

        print("Error");

      print("result = $result");

    }



    enter +,-,*,%
    *
    result = 105

    enter +,-,*,%
    /
    Error
    result = null

    With switch case statement, the code become like that :


    import 'dart:io';

     

    void main() {

      print("enter +,-,*,%");

      String oper = stdin.readLineSync();

      int x = 15, y = 7, result;

      switch (oper) {

        case "+":

          {

            result = x + y;

          }

          break;

        case "-":

          {

            result = x - y;

          }

          break;

        case "*":

          {

            result = x * y;

          }

          break;

        case "%":

          {

            result = x % y;

          }

          break;

        default:

          {

            print("Error");

          }

          break;

      }

      print("result = $result");

    }



    enter +,-,*,%
    %
    result = 1

    /
    Error
    result = null