Open In App

Fallthrough Condition in Dart

Improve
Improve
Like Article
Like
Save
Share
Report

Fall through is a type of error that occurs in various programming languages like C, C++, Java, Dart …etc. It occurs in switch-case statements where when we forget to add break statement and in that case flow of control jumps to the next line. 

“If no break appears, the flow of control will fall through all the cases following true case
until the break is reached or end of the switch is reached.”

So, it is clear that the most basic way of creating the situation of fall through is skipping the break statements in Dart, but in the dart, it will give a compilation error.

Example 1: Skipping break statements
 

Dart




// This code will display error
void main() {
  int gfg = 1;
  switch ( gfg ){
    case 1:{
      print("GeeksforGeeks number 1");
    }
    case 2:{
      print("GeeksforGeeks number 2");
    }
    case 3:{
      print("GeeksforGeeks number 3");
    }
    default :{
      print("This is default case");
    }
  }
}


 

Error:  

Error compiling to JavaScript:
main.dart:4:5:
Error: Switch case may fall through to the next case.
    case 1:{
    ^
main.dart:7:5:
Error: Switch case may fall through to the next case.
    case 2:{
    ^
main.dart:10:5:
Error: Switch case may fall through to the next case.
    case 3:{
    ^
Error: Compilation failed.

However, it allows skipping of break statement in the case when there is only one case statement defined.

Note: It must be noted that Dart allows empty cases.

Example 2: Providing an empty case. 
 

Dart




void main() {
    
  // Declaring value
  // of the variable
  int gfg = 2;
  switch ( gfg ){
    case 1:{
      print("GeeksforGeeks number 1");
    } break;
        
    // Empty case causes fall through
    case 2: 
    case 3:{
      print("GeeksforGeeks number 3");
    } break;
    default :{
      print("This is default case");
    } break;
  }
}


 

Output:  

GeeksforGeeks number 3

In the above code if we initialize the value of gfg = 3 than the output will not change. Another way to achieve fall through is via using continue instead of break statement in switch-case.

Example 3: Using continue instead of break 
 

Dart




void main() {
  int gfg = 1;
  switch ( gfg ){
    case 1:{
      print("GeeksforGeeks number 1");
    } continue next;
    next:case 2:{
      print("GeeksforGeeks number 2");
    } break;
    case 3:{
      print("GeeksforGeeks number 3");
    } break;
    default :{
      print("This is default case");
    } break;
  }
}


 

Output:  

GeeksforGeeks number 1
GeeksforGeeks number 2

Note: It must be noted that if we will not declare label with continue in the above code than the code will display error.



Last Updated : 20 Jul, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads