typestar

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

  1. The if rejects scores outside 0 to 100 before any bucketing happens.
  2. switch (score / 25) folds the range into five buckets with integer division.
  3. case 4 falls through to case 3: a perfect 100 earns the same label as 75 and up.
  4. return ends each case, so no break is needed; default catches everything left.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Control flow, step 4 of 27 in Language basics.

← Previous Next →