Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Procedures and Control Flow

Decisions: if, case and when

Learn Nim conditionals: if/elif/else as statements and expressions, case with ranges and strings, and the compile-time when statement with defined(), with C stand-ins.

Programs branch. Nim gives you three tools: if for ordinary run-time decisions, case for choosing between many values, and when for choices the compiler makes before the program runs. In all three, blocks are marked by indentation, and the conditions need no parentheses.

Nim snippets are read-only on this site; the C blocks are runnable stand-ins.

if, elif, else

NIM
let temperature = 28

if temperature > 30:
  echo "hot"
elif temperature > 20:
  echo "warm"
else:
  echo "cool"

The condition must be a bool. After the colon comes an indented block (or a short statement on the same line: if x: echo "yes"). The word is elif, not else if.

if as an expression

Because Nim is expression-oriented, if can produce a value. Every branch must have the same type and an else is required:

NIM
let label = if temperature > 25: "summer" else: "other"
let parity = if 7 mod 2 == 0: "even" else: "odd"
echo label, " ", parity

This replaces the ternary operator from C-like languages.

case

Use case when one value is compared against many options:

NIM
let day = 3
case day
of 1: echo "Monday"
of 2: echo "Tuesday"
of 3: echo "Wednesday"
of 6, 7: echo "Weekend"
else: echo "Unknown"

Notable rules:

  • Every possible value must be handled. For integers and strings this means an else branch. For enums and bool, covering all members is enough, and the compiler will tell you when you forget one.
  • Several values share a branch with a comma: of 6, 7:.
  • Ranges are allowed: of 1 .. 5:. Characters work too: of 'a' .. 'z':.
  • Matching is by equality and there is no fall-through; each branch ends on its own, so you never write break.
  • It also works on strings.
NIM
func category(score: int): string =
  case score
  of 90 .. 100: "A"
  of 80 .. 89: "B"
  of 70 .. 79: "C"
  else: "needs work"

let command = "stop"
case command
of "go": echo "moving"
of "stop", "halt": echo "stopped"
else: echo "?"

As in if, case can be used as an expression: the category function above returns the value of the matching branch directly.

when: decisions at compile time

when looks like if, but its condition is evaluated by the compiler, and only the winning branch is compiled at all. The other branches do not even have to be valid on this platform:

NIM
when defined(windows):
  const separator = '\\'
else:
  const separator = '/'

when sizeof(int) == 8:
  echo "64-bit build"
else:
  echo "32-bit build"

Typical uses:

Purpose Example
Platform-specific code when defined(linux):
Build flavor when defined(release): or when defined(debug):
Custom flags when defined(myFeature): (compile with -d:myFeature)
Run only as the main program when isMainModule:
Type-dependent code when T is int: inside generics

when isMainModule: is a common pattern in library files: the block runs when the file is compiled as the program but not when another file imports it, so a module can include its own demo or tests.

Unlike if, a when branch does not create a new scope, so declarations inside it are visible after it. That is what lets the separator constant above be used later in the file.

flowchart TD
  S["source file"] --> W{"when condition<br/>(compile time)"}
  W -- "true" --> A["branch A is compiled"]
  W -- "false" --> B["branch B is compiled"]
  A --> X["only one branch<br/>exists in the program"]
  B --> X

Caption: the compiler discards the branch that does not apply, so there is no run-time check.

Truthiness is strict

Nim never treats numbers, strings or collections as true or false on their own. if items: for a sequence does not compile; write if items.len > 0: or if items.len != 0:. The extra words buy you safety.

Stand-in: switch with ranges and the preprocessor

GCC and Clang support case ranges in C, which is a close match to of 90 .. 100:. The #if blocks play the role of when, deciding at compile time. This is C, not Nim.

C Stand-in: case ranges and compile-time choice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Set BUILD_FLAG to 0 and run again: the other branch is the only one left in the program, just like a when in Nim.

Stand-in: no fall-through

C's switch falls through unless you write break, which is a classic bug source. This stand-in shows the behavior Nim's case never has.

C Stand-in: fall-through is a C hazard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

In Nim the two values share a branch with of 6, 7: and nothing runs afterwards.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What keyword does Nim use for "else if"?

    Nim spells it elif.
  2. 2. A case statement over an int must...

    case must be exhaustive; for integers and strings that means an else branch.
  3. 3. What is special about when?

    when is compile-time branching, used for platforms, flags and generic code.
  4. 4. Which is a valid if-expression?

    An if-expression needs an else branch and matching types.

Summary

  • if/elif/else branches at run time and can be an expression when it has an else.
  • case compares one value against many; it supports multiple values and ranges, has no fall-through and must be exhaustive.
  • when is the compile-time version, used with defined(...), isMainModule and type checks; its branches add no scope.
  • Conditions must be real booleans.

Next: Loops and ranges