0
Switch Statement Vs if-else statement
Lets say I want to write a program that asks users for a score (0-100) and assign a letter grade (A-E) to the score, is it possible to use a switch statement (without having 101 cases) or if-else statement is better? . . . int score; if ((score >= 80) && (score < 90)) cout << "You've got a B\n"; else if ((score >= 70) && (score < 80)) cout << "You've got a C\n"; . . .
3 Answers
+ 10
If you need to check ranges (like you would do for a grading system), you must use if/else. A switch only checks for specific, single values.
+ 1
with GCC and LLVM/Clang, both support ranges in switch case statement. Not sure if this is in the language standard or just compiler extension.
Here is how it looks:
switch(marks){
case 1 ... 49: printf("fail"); break;
case 50 ... 64: printf("credit"); break;
...
...
}
+ 1
With a switch, you can run the same code for multiple cases, but you can't include an inequality/range.
switch(score){
case 1:
case 2:
case 3:
grade = "C";
break;
case 4:
case 5:
case 6:
grade = "B";
break;
default:
grade = "A";
}
OR
if (score < 4){
grade = "C";
}
else if (score < 7){
grade = "B";
}
else {
grade = "A"
}
Seems like the if else statements are easier.