If & switch in C++
Guard the weird input with if, then let switch fan the normal range out into cases.
#include <string>
std::string grade_label(int score) {
if (score < 0 || score > 100) {
return "invalid";
}
switch (score / 25) {
case 4:
case 3:
return "pass";
case 2:
return "retry";
default:
return "fail";
}
}
How it works
- The
ifrejects scores outside 0 to 100 before any bucketing happens. switch (score / 25)folds the range into five buckets with integer division.case 4falls through tocase 3: a perfect 100 earns the same label as 75 and up.returnends each case, so nobreakis needed;defaultcatches everything left.
Keywords and builtins used here
casedefaultgrade_labelifintreturnswitch
The run, in numbers
- Lines
- 16
- Characters to type
- 212
- Tokens
- 66
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 50 seconds.
Step 1 of 3 in Control flow, step 4 of 27 in Language basics.