Switch
- Switch Flow Control
- Syntax :
- Example
The switch statement allows us to replace several nested if-else constructs and thus improve the readability of our code.
switch(variable_expression) {
case constant_expr1: {
// statements;
}
break;
case constant_expr2: {
//statements;
}
break;
default: {
//statements;
}
break;
}
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");
}
*
result = 105
/
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");
}
%
result = 1
Error
result = null