Inherited from v1.0.0

switch / case / default

switch matches a single value against a list of case blocks and runs the first one that matches. There is no fall-through — each block runs at most once, and control then exits the switch.

Bangla forms: বিকল্প / অবস্থা / অন্যথায়.

Syntax

switch (<subject>) {
    case <value1>: { <statements> }
    case <value2>:
    case <value3>: { <shared statements> }
    default: { <fallback statements> }
}

Each case's body is required to be wrapped in { ... }. Multiple case <value>: lines stacked before a single block share that block.

Examples

function describe(n) {
    switch (n) {
        case 1: { return "one"; }
        case 2:
        case 3: { return "two or three"; }
        default: { return "other"; }
    }
}

print(describe(1));    // one
print(describe(2));    // two or three
print(describe(99));   // other

Matching uses bnl's == semantics — types must match, no implicit coercion:

switch ("red") {
    case "red":   { print("RGB 255 0 0"); }
    case "green": { print("RGB 0 255 0"); }
    default:      { print("unknown"); }
}

Early exit with break

You can write break; inside a case to exit the switch early. Falling off the end of the case body has the same effect, so break is rarely needed — it's there for parity with loops:

switch (n) {
    case 0: {
        print("zero");
        break;            // optional — the case body would end here anyway
    }
    default: { print("nonzero"); }
}

No fall-through

If you're coming from C or JavaScript: case in bnl does not fall through. The block runs and the switch ends. Use stacked cases (case X: case Y: { body }) when you need one body for multiple values.

Bangla form

ফাংশন describe(n) {
    বিকল্প (n) {
        অবস্থা 1: { ফেরত "এক"; }
        অবস্থা 2: { ফেরত "দুই"; }
        অন্যথায়: { ফেরত "অন্য"; }
    }
}

See also

  • break — explicit exit from a case.
  • if / else — for non-equality conditions.