Fallthrough Condition in Dart
Last Updated :
20 Jul, 2020
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;
}
}