Taskintro
Write a switch or match
Also called switch on a value, match on a value, case statement, when expression, days in a month, multi-way branch.
Map a month number to its number of days with one switch or match, put several values in one case, and give a default case for the values that are not months.
- Evidence
- Code in 10 languages
Task
Choose a branch by the value of one expression with a switch, a match or a case. The function days_in_month(month) takes a month number and returns the number of days in that month of a common year, that is, a year that is not a leap year:
28for month 2,30for months 4, 6, 9 and 11,31for months 1, 3, 5, 7, 8, 10 and 12,0for any other int, such as 0, 13 or -1.
For example, days_in_month(4) is 30 and days_in_month(13) is 0.
Eleven of the twelve months share a result with other months. So the solution must put several values in one case, and it needs a default case for the values that are not months. Write a conditional chooses a branch with a chain of tests. Switch statement explains the construct itself.
Solutions
| Language | Several values in one case | The default case | If no case matches and there is no default |
|---|---|---|---|
| Python | case 4 | 6 | 9 | 11:1 |
case _:1 |
no branch runs1 |
| JavaScript, TypeScript | case 4: case 6: and so on, one label on each line |
default:2 |
the program continues after the switch2 |
| Java | case 4, 6, 9, 11 ->3 |
default -> |
a compile error, because a switch expression must be exhaustive3 |
| C# | 4 or 6 or 9 or 11 =>4 |
_ => |
a compiler warning, and an exception at run time5 |
| C, C++ | case 4: case 6: and so on, one label on each line |
default: |
no part of the switch body runs67 |
| Go | case 4, 6, 9, 11:8 |
default:8 |
no case runs8 |
| Rust | 4 | 6 | 9 | 11 =>9 |
_ => |
a compile error, because a match must be exhaustive10 |
| Bash | 4 | 6 | 9 | 11)11 |
*)11 |
no command list runs11 |
| Kotlin | 4, 6, 9, 11 ->12 |
else ->12 |
a compile error when when is an expression12 |
- Python. A
matchstatement tries the cases from the top, and "Only the first pattern that matches gets executed"1. The tutorial also states that "You can combine several literals in a single pattern using | (“or”)"1. The last case uses_, which "acts as a wildcard and never fails to match"1. - JavaScript and TypeScript. A
switch"looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using the strict equality comparison)"2. An emptycaselabel does nothing, so control goes on to the next label. This is how several labels share one body. Each body ends withreturn, so no body runs on into the next one. - Java. The solution uses a switch expression with arrow labels. The arrow syntax "supports multiple constants per case, separated by commas"3, and each arm runs only its own code. Without the
defaultarm, the code does not compile, because "The cases of a switch expression must be exhaustive"3. - C#. The solution uses a switch expression. The
orpattern "matches an expression when either pattern matches the expression"4. The_arm catches the other values. - C and C++. These languages have no list of values in one label, so the solution stacks the labels. Each group ends with
return. If no label matches and there is nodefault, "no part of the switch body is executed"6. cppreference states the same rule for C++: "none of the statements in the switch statement will be executed"7. - Go. A case holds a list of expressions, such as
case 4, 6, 9, 11:8. A Go case does not run on into the next case. At the end of a case, control goes to the end of theswitch, unless the case ends with afallthroughstatement8. - Rust. In a
match, "you can match multiple patterns using the | syntax, which is the pattern or operator"9. The_arm is necessary, because the arms must cover each value ofi3210. - Bash. In a
casecommand, "The ‘|’ is used to separate multiple patterns in a pattern list"11. The last pattern is*: "It’s a common idiom to use ‘*’ as the final pattern to define the default case, since that pattern will always match"11. - Kotlin. This task has no Kotlin solution, but Kotlin
whendoes the same work.when"evaluates its argument and compares the result against each branch in order until one branch condition is satisfied"12. Commas put several conditions in one branch12. Whenwhenis an expression, "an else branch is required"12 in the general case.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
december: the last month. A month list that stops at 11 gives0for it.zero,thirteenandminus-one: values that are not months. Only the default case gives0for them.
Pitfalls
- A missing break. In C, C++, JavaScript, and Java statements with colon labels, a body without
breakorreturnruns on into the next body. In C++, "case and default labels in themselves do not alter the flow of control"7. A JavaScriptswitchruns the statements after the matching clause "until a break statement is encountered"2. The Java tutorial states: "The break statements are necessary because without them, statements in switch blocks fall through"13. Here the body for February setsdaysto 28, and then the body for April sets it to 30:
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
static int days_in_month(int month) {
int days = 0;
switch (month) {
case 2:
days = 28;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
}
return days;
}
int main(void) {
printf("%d %d %d\n", days_in_month(2), days_in_month(4), days_in_month(1));
return 0;
}
30 30 31
A break after days = 28; gives 28 for February. Fall-through explains this behavior and the languages that do not have it.
- A default that hides bad input. A default case that returns a real result makes the code shorter, but then a bad value gets that result too. Here
defaultstands for the months with 31 days, so month 13 gets 31 days:
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
func daysInMonth(month int) int {
switch month {
case 2:
return 28
case 4, 6, 9, 11:
return 30
default:
return 31
}
}
func main() {
fmt.Println(daysInMonth(1), daysInMonth(13), daysInMonth(-1))
}
31 31 31
Give each valid value its own case, and keep the default case for the values that are not valid.
- A switch with no default. A switch statement without a default case does nothing for a value that no case matches. The Java tutorial warns: "This may be a place for bugs to hide in your application, something you want to avoid"3. Rust does not compile a
matchthat misses a value: "Matches in Rust are exhaustive: We must exhaust every last possibility in order for the code to be valid"10. This version has no_arm:
This code does not compile, on purpose.
fn days_in_month(month: i32) -> i32 {
match month {
2 => 28,
4 | 6 | 9 | 11 => 30,
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
}
}
fn main() {
println!("{}", days_in_month(2));
}
The compiler reports error E0004, non-exhaustive patterns10. A _ => 0 arm fixes it.
- A name in a Python case. In Python,
case QUIT:does not compare the value with the variableQUIT. It is a capture pattern: "A capture pattern binds the subject value to a name", and "Capture patterns always succeed"14. So the case matches each value. Switch statement shows this mistake. A dotted name such ascase Color.RED:is a value pattern, and it "succeeds if the value found compares equal to the subject value"14. Literals such ascase 2:also compare the value14.
Related tasks
- Write a conditional: choose a branch with a chain of tests.
- Switch statement: the concept of a switch statement in each language.
- Fall-through: the concept of a case that runs on into the next case.
- Pattern matching: a match that also takes a value apart.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-switch-or-match/.
def days_in_month(month: int) -> int:
"""Return the number of days in a month of a common year, or 0 for a bad month."""
match month:
case 2:
return 28
case 4 | 6 | 9 | 11:
return 30
case 1 | 3 | 5 | 7 | 8 | 10 | 12:
return 31
case _:
return 0
test_days_in_month.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-switch-or-match/.
import pytest
from days_in_month import days_in_month
CASES = {
"january": (1, 31),
"february": (2, 28),
"april": (4, 30),
"july": (7, 31),
"november": (11, 30),
"december": (12, 31),
"zero": (0, 0),
"thirteen": (13, 0),
"minus-one": (-1, 0),
}
@pytest.mark.parametrize("name", CASES)
def test_days_in_month(name):
month, want = CASES[name]
assert days_in_month(month) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
#include "days_in_month.hpp"
int days_in_month(int month) {
switch (month) {
case 2:
return 28;
case 4:
case 6:
case 9:
case 11:
return 30;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
default:
return 0;
}
}
days_in_month.hpp 8 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
#pragma once
// days_in_month returns the number of days in a month of a common year, or 0
// for a month outside 1 to 12.
int days_in_month(int month);
test_days_in_month.cpp 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
#include "days_in_month.hpp"
#include <iostream>
#include <string_view>
static int failures = 0;
static void check(std::string_view name, int month, int want) {
if (days_in_month(month) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("january", 1, 31);
check("february", 2, 28);
check("april", 4, 30);
check("july", 7, 31);
check("november", 11, 30);
check("december", 12, 31);
check("zero", 0, 0);
check("thirteen", 13, 0);
check("minus-one", -1, 0);
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
final class DaysInMonth {
private DaysInMonth() {}
/** Returns the number of days in a month of a common year, or 0 for a bad month. */
static int daysInMonth(int month) {
// A switch expression: each case -> runs only its own code.
return switch (month) {
case 2 -> 28;
case 4, 6, 9, 11 -> 30;
case 1, 3, 5, 7, 8, 10, 12 -> 31;
default -> 0;
};
}
}
DaysInMonthTest.java 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class DaysInMonthTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("january", 1, 31),
Arguments.of("february", 2, 28),
Arguments.of("april", 4, 30),
Arguments.of("july", 7, 31),
Arguments.of("november", 11, 30),
Arguments.of("december", 12, 31),
Arguments.of("zero", 0, 0),
Arguments.of("thirteen", 13, 0),
Arguments.of("minus-one", -1, 0));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void daysInMonth(String name, int month, int want) {
assertEquals(want, DaysInMonth.daysInMonth(month), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
#include "days_in_month.h"
int days_in_month(int month) {
// Each group of labels ends with return, so no case falls through.
switch (month) {
case 2:
return 28;
case 4:
case 6:
case 9:
case 11:
return 30;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
default:
return 0;
}
}
days_in_month.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
#ifndef DAYS_IN_MONTH_H
#define DAYS_IN_MONTH_H
// days_in_month returns the number of days in a month of a common year, or 0
// for a month outside 1 to 12.
int days_in_month(int month);
#endif
test_days_in_month.c 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
#include "days_in_month.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *name, int month, int want) {
if (days_in_month(month) != want) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
}
int main(void) {
check("january", 1, 31);
check("february", 2, 28);
check("april", 4, 30);
check("july", 7, 31);
check("november", 11, 30);
check("december", 12, 31);
check("zero", 0, 0);
check("thirteen", 13, 0);
check("minus-one", -1, 0);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
public static class DaysInMonth
{
// Returns the number of days in a month of a common year, or 0 for a bad month.
public static int Of(int month) => month switch
{
2 => 28,
4 or 6 or 9 or 11 => 30,
1 or 3 or 5 or 7 or 8 or 10 or 12 => 31,
_ => 0,
};
}
DaysInMonthTests.cs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
using Xunit;
public sealed class DaysInMonthTests
{
public static TheoryData<string, int, int> Cases => new()
{
{ "january", 1, 31 },
{ "february", 2, 28 },
{ "april", 4, 30 },
{ "july", 7, 31 },
{ "november", 11, 30 },
{ "december", 12, 31 },
{ "zero", 0, 0 },
{ "thirteen", 13, 0 },
{ "minus-one", -1, 0 },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int month, int want)
{
Assert.NotNull(name);
Assert.Equal(want, DaysInMonth.Of(month));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
/**
* Returns the number of days in a month of a common year, or 0 for a bad month.
* @param {number} month
* @returns {number}
*/
export function daysInMonth(month) {
switch (month) {
case 2:
return 28;
case 4:
case 6:
case 9:
case 11:
return 30;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
default:
return 0;
}
}
days_in_month.test.js 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { daysInMonth } from "./days_in_month.js";
const cases = [
["january", 1, 31],
["february", 2, 28],
["april", 4, 30],
["july", 7, 31],
["november", 11, 30],
["december", 12, 31],
["zero", 0, 0],
["thirteen", 13, 0],
["minus-one", -1, 0],
];
for (const [name, month, want] of cases) {
test(name, () => {
assert.equal(daysInMonth(month), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
/** Returns the number of days in a month of a common year, or 0 for a bad month. */
export function daysInMonth(month: number): number {
switch (month) {
case 2:
return 28;
case 4:
case 6:
case 9:
case 11:
return 30;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
default:
return 0;
}
}
days_in_month.test.ts 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { daysInMonth } from "./days_in_month.ts";
const cases: [string, number, number][] = [
["january", 1, 31],
["february", 2, 28],
["april", 4, 30],
["july", 7, 31],
["november", 11, 30],
["december", 12, 31],
["zero", 0, 0],
["thirteen", 13, 0],
["minus-one", -1, 0],
];
for (const [name, month, want] of cases) {
test(name, () => {
assert.equal(daysInMonth(month), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
// Package daysinmonth maps a month number to its number of days.
package daysinmonth
// DaysInMonth returns the number of days in a month of a common year, or 0
// for a month outside 1 to 12.
func DaysInMonth(month int) int {
// A Go case ends by itself, so no break is needed.
switch month {
case 2:
return 28
case 4, 6, 9, 11:
return 30
case 1, 3, 5, 7, 8, 10, 12:
return 31
default:
return 0
}
}
days_in_month_test.go 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
package daysinmonth
import "testing"
var cases = []struct {
name string
month int
want int
}{
{"january", 1, 31},
{"february", 2, 28},
{"april", 4, 30},
{"july", 7, 31},
{"november", 11, 30},
{"december", 12, 31},
{"zero", 0, 0},
{"thirteen", 13, 0},
{"minus-one", -1, 0},
}
func TestDaysInMonth(t *testing.T) {
for _, c := range cases {
if got := DaysInMonth(c.month); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
/// Returns the number of days in a month of a common year, or 0 for a bad month.
pub fn days_in_month(month: i32) -> i32 {
// match must cover every i32, so the last arm is _.
match month {
2 => 28,
4 | 6 | 9 | 11 => 30,
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
_ => 0,
}
}
tests/days_in_month_test.rs 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-switch-or-match/.
use algo_write_a_switch_or_match::days_in_month;
#[test]
fn cases() {
let cases: &[(&str, i32, i32)] = &[
("january", 1, 31),
("february", 2, 28),
("april", 4, 30),
("july", 7, 31),
("november", 11, 30),
("december", 12, 31),
("zero", 0, 0),
("thirteen", 13, 0),
("minus-one", -1, 0),
];
for &(name, month, want) in cases {
assert_eq!(days_in_month(month), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-switch-or-match/.
# days_in_month MONTH
# Prints the number of days in a month of a common year, or 0 for a bad month.
days_in_month() {
case $1 in
2)
printf '%s\n' 28
;;
4 | 6 | 9 | 11)
printf '%s\n' 30
;;
1 | 3 | 5 | 7 | 8 | 10 | 12)
printf '%s\n' 31
;;
*)
printf '%s\n' 0
;;
esac
}
test_days_in_month.bats 23 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-switch-or-match/.
setup() {
source "$BATS_TEST_DIRNAME/days_in_month.sh"
}
check() { # check MONTH WANT
local got
got=$(days_in_month "$1")
[ "$got" = "$2" ] || { printf 'got: %s\nwant: %s\n' "$got" "$2"; return 1; }
}
@test "january" { check 1 31; }
@test "february" { check 2 28; }
@test "april" { check 4 30; }
@test "july" { check 7 31; }
@test "november" { check 11 30; }
@test "december" { check 12 31; }
@test "zero" { check 0 0; }
@test "thirteen" { check 13 0; }
@test "minus-one" { check -1 0; }
References
- More Control Flow Tools, The Python Tutorial, 4.7 match Statements
- switch, MDN Web Docs, Description
- Branching with Switch Expressions, Dev.java, Modifying the Switch Syntax; Producing a Value; Adding a Default Clause
- Pattern matching, C# language reference, Logical patterns
- switch expression, C# language reference, Nonexhaustive switch expressions
- N1570, ISO/IEC 9899:201x Committee Draft (C11), 6.8.4.2 The switch statement, paragraph 5
- switch statement, cppreference.com, Control flow transfer
- The Go Programming Language Specification, Switch statements; Expression switches
- Pattern Syntax, The Rust Programming Language, Matching Multiple Patterns
- The match Control Flow Construct, The Rust Programming Language, Matches Are Exhaustive
- Conditional Constructs, Bash Reference Manual, case
- Conditions and loops, Kotlin documentation, When expressions and statements
- Branching with Switch Statements, Dev.java, Using Switch Statements to Control the Flow of Your Program
- Compound statements, The Python Language Reference, 8.6.4.3 Literal Patterns; 8.6.4.4 Capture Patterns; 8.6.4.6 Value Patterns
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 7Q1CXC Edit this page History Report an error Markdown