Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 36 ยท Basics and Types

Booleans, Characters and Operators

Learn Nim's bool and char types, and, or, not, short-circuit logic, comparison, the in operator with sets, string concatenation, precedence rules and custom operators.

Decisions need truth values, and text needs characters. In this lesson you meet bool and char, the operators that combine them, and the rules Nim uses to decide which operator binds tighter. Nim's operators are ordinary procedures with symbolic names, which is why you can also define your own.

The Nim blocks are read-only because the compiler cannot run on this site; C stand-ins that run here demonstrate the logic.

bool

A bool has exactly two values, true and false. Comparisons produce them:

NIM
let age = 20
let adult = age >= 18          # true
let isZero = age == 0          # false
echo adult, " ", isZero        # true false

The comparison operators are ==, !=, <, <=, > and >=. There is no implicit conversion between integers and booleans: if 1: is a compile error. This avoids a whole family of C mistakes where = and == are confused.

Logical operators

NIM
echo true and false     # false
echo true or false      # true
echo not true           # false
echo true xor true      # false

and and or are short-circuiting: the right side is evaluated only if the left side has not already decided the answer. This is how you guard against errors:

NIM
let items: seq[int] = @[]
if items.len > 0 and items[0] == 5:
  echo "starts with five"

If items.len > 0 is false, items[0] is never evaluated, so there is no index error.

char

A char is a single byte, written in single quotes: 'a', '7', '\n'. It is an ordinal type, so you can convert to and from numbers with ord and chr:

NIM
let c = 'A'
echo ord(c)             # 65
echo chr(ord(c) + 1)    # B
echo c < 'B'            # true

Common escapes inside character and string literals are \n (newline), \t (tab), \\ (backslash), \', \" and \xHH (a byte in hex). A char holds one byte, so it cannot hold an arbitrary Unicode character; use Rune for that (strings and runes).

Ranges and sets of characters read nicely:

NIM
import std/strutils
let ch = 'x'
echo ch in {'a'..'z'}              # true
echo ch in {'0'..'9'}              # false
echo toUpperAscii(ch)              # X
echo isAlphaAscii(ch)              # true

Membership and identity operators

Operator Meaning Example
in, notin membership in a set, range, seq, string or table 3 in 1..5
is compile-time type test x is int
of run-time object type test animal of Dog
& concatenate strings (and sequences) "a" & "b"
$ convert to string $42 is "42"
NIM
echo 3 in 1 .. 5          # true
echo "ell" in "hello"     # true  (substring test)
echo 10 notin [1, 2, 3]   # true
echo "n=" & $5            # n=5

Precedence

When an expression has several operators, precedence decides the grouping. Nim determines the precedence of most operators by their first character. From strongest to weakest:

Level Operators
10 $, ^
9 *, /, div, mod, shl, shr, %
8 +, -, ~, | (first-character rules)
7 &
6 ..
5 ==, <, <=, in, is, of, and similar
4 and
3 or, xor

A key point: not is a unary operator that binds tightly, while and is weaker than comparisons, so a > 1 and b < 5 needs no parentheses. Also, & binds tighter than ==. When in doubt, add parentheses; they are free.

NIM
echo 2 + 3 * 4          # 14
echo (2 + 3) * 4        # 20
echo not (1 > 2)        # true

The dot in a.b and the call syntax f(x) bind tighter than any operator in the table.

Defining your own operator

Operators are procedures whose names are written in backticks:

NIM
proc `+++`(a, b: string): string =
  a & " " & b

echo "hello" +++ "world"    # hello world

Because precedence comes from the first character, +++ has the same precedence as +. Use this sparingly; a well-named procedure is usually clearer.

Stand-in: short-circuit and precedence in C

C has the same short-circuit behavior for && and ||. This stand-in uses a function with a side effect to prove that the right operand is skipped, then prints a few precedence results.

C Stand-in: short-circuit evaluation

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.

Only the left operands "A" are evaluated. This guard behavior is what makes patterns like x.len > 0 and x[0] == 5 safe in Nim as well.

Stand-in: char arithmetic

C Stand-in: ord, chr and ranges

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.

The 'a'..'z' idiom in Nim hides the same two comparisons.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does short-circuit evaluation mean for a and b?

    When a is false the answer is already known, so b is skipped.
  2. 2. Which expression is true in Nim?

    Character sets and ranges work with in. Integers are not booleans, and 'abc' is not a valid char literal.
  3. 3. What is a Nim char?

    A char is one byte. Use Rune for Unicode characters.
  4. 4. What does $ do?

    $x calls the string conversion. & is concatenation.

Summary

  • bool has true and false; there are no implicit conversions from integers.
  • and and or short-circuit; not and xor also exist; the same words are bitwise on integers.
  • char is a single byte; ord and chr convert to and from numbers.
  • in, is, of, & and $ are everyday operators; precedence follows the first character, so use parentheses when unsure.
  • You can define operators with backticks.

Next: Type conversions and distinct types