Skip to content

Switch Statement

IsaacShelton edited this page Mar 21, 2022 · 1 revision

Switch Statement

Switch statements are used to execute one of many different blocks depending on a single value

switch integer_like {
case 1
    // ...
case 4
    // ...
default
    // ...
}

switch my_enum {
case MyEnum::VALUE_ONE
    // ...
case MyEnum::VALUE_TWO
    // ...
default
    // ...
}

Unlike in C and other languages, break is not used to terminate cases.

Exhaustive

The exhaustive keyword can be used to ensure a switch statement covers all possible cases of an enum value

exhaustive switch car_color {
case CarColor::BLACK, print("A nice black car!")
case CarColor::GREY,  print("An awesome grey car!")
case CarColor::WHITE, print("A clean white car!")
case CarColor::RED,   print("A fierce red car!")
}

A compile-time error will occur if a case is missing from an exhaustive switch statement.

Fallthrough

By default, cases don't fall through into the next block. To have a case fall though into the next, you can use the fallthrough statement

switch animal_kind {
case AnimalKind::CAT
    fallthrough
case AnimalKind::DOG
    print("The animal is a cat or dog")
}

Since fallthrough is a statement, it can be used inside of conditional statements

switch animal_kind {
case AnimalKind::CAT
    if animal_sub_kind != AnimalSubKind::TIGER {
        fallthrough
    }
    print("The animal is a tiger")
case AnimalKind::DOG
    print("The animal is a cat or dog")
}

Condensed Switch

Switch statements can be written more concisely by using cases and statements on the same line by ending case values with a ,

switch color {
case Color::RED,   return "Red"
case Color::BLUE,  return "Blue"
case Color::GREEN, return "Green"
default            return "Unknown Color"
}
Clone this wiki locally