Switch Statement

  • Switch Statement

Switch Statement

The switch Statement evaluates an expression, matches the expression’s value to a case clausee and executes the statements associated with that case. It is an alternative to the long if-else-if ladder which is a easy way to execute a different part of a code on the value of the expression.

what is switch statment in dart?

The switch statement in dart is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression.

Syntax

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

The value of the variable_expression is tested against all cases in the switch,if matches the code block is executed right away, If no expression is matched the default block is executed.

What are the rules for switch case?

Rules to be followed:

  • Only constats expression are included not variable_expression.
  • The datat type of both the constant and varibale must matched.
  • break is must to put a break in execution flow.
  • Case expression must be unique and default block is optional Example for switch case
void main(){
  var grade = "A";
  switch(grade){
  case "A": { 
     print("Excellent"); } 
      break; 
     
  case "B": {  
    print("Good"); 
    } 
      break; 
     
  case "C": { 
     print("Fair"); 
     } 
      break; 
    
  case "D": { 
    print("Poor");
     } 
      break; 
     
  default: {
     print("Invalid choice"); 
     } 
      break; 
   } 
}  

The output is :-

Excellent

code Try Yourself