Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท Procedures and Control Flow

Parameters, Overloading and UFCS

Understand how Nim passes arguments, mutate callers' values with var parameters, accept lists with openArray and varargs, overload procedures, and chain calls with UFCS.

How does a procedure receive its arguments, and can it change the caller's variables? Nim answers with a simple default (parameters are read-only) and an explicit opt-in (var). On top of that you get overloading, which lets several procedures share a name, and UFCS, which lets you write x.f(y) instead of f(x, y). Together these give Nim its "method" feel without needing classes.

The Nim snippets are read-only (no compiler on this site). The C stand-ins can be edited and run.

Parameters are read-only

Inside a procedure, a normal parameter cannot be assigned to:

NIM
proc shout(s: string): string =
  s = s & "!"             # error: 's' cannot be assigned to
  s

The compiler may pass large values by reference behind the scenes for speed, but for you they behave as immutable. To get a modified copy, make one:

NIM
proc shout(s: string): string =
  var copy = s
  copy.add "!"
  copy

Or just return the new value: s & "!".

var parameters: changing the caller's variable

To mutate the argument itself, declare the parameter var:

NIM
proc double(x: var int) =
  x *= 2

var n = 21
double(n)
echo n                # 42

The caller must pass a variable (var, not let, not a literal): double(5) is a compile error. This makes mutation visible in the signature, so you can tell from the first line of a procedure whether it changes its arguments. A common use is a procedure that fills in a collection:

NIM
proc addAll(target: var seq[int], items: openArray[int]) =
  for x in items:
    target.add x

Lists of arguments

openArray[T] accepts an array, a seq or a slice of either, without copying, so it is the right type for read-only list parameters.

NIM
func total(values: openArray[int]): int =
  for v in values:
    result += v

echo total([1, 2, 3])              # works with an array
echo total(@[4, 5, 6])             # and a seq

varargs[T] lets the caller pass any number of arguments, which arrive as an openArray:

NIM
proc printAll(items: varargs[string]) =
  for item in items:
    echo item

printAll("a", "b", "c")

Overloading

Several procedures may share a name if their parameter types or counts differ. The compiler picks the best match at compile time:

NIM
proc describe(x: int): string = "int " & $x
proc describe(x: float): string = "float " & $x
proc describe(x: string): string = "string " & x
proc describe(x: int, y: int): string = "pair " & $x & "," & $y

echo describe(1)           # int 1
echo describe(2.5)         # float 2.5
echo describe("hi")        # string hi
echo describe(3, 4)        # pair 3,4

This is how echo, $ and + work on many types. If two overloads fit equally well, the compiler reports an ambiguous call error. Overloading also works on the return type only in rare cases; prefer distinct parameters.

flowchart TD
  C["describe(2.5)"] --> M{"compiler matches<br/>argument types"}
  M -->|"int"| A["describe(x: int)"]
  M -->|"float"| B["describe(x: float)"]
  M -->|"string"| S["describe(x: string)"]

Caption: overload resolution happens at compile time, so it costs nothing at run time.

UFCS: Uniform Function Call Syntax

Any procedure can be called with the first argument written before a dot:

NIM
import std/strutils

echo toUpperAscii("nim")           # classic call
echo "nim".toUpperAscii()          # UFCS: first argument before the dot
echo "nim".toUpperAscii            # no parentheses needed if no more arguments
echo "a,b,c".split(',').len        # chain: split, then len  -> 3

x.f(y) is nothing more than f(x, y). That lets you add "methods" to types you did not write: define proc isShort(s: string): bool and then call "abc".isShort. It also produces readable left-to-right pipelines:

NIM
let words = "  The quick brown fox  ".strip().toLowerAscii().split(' ')
echo words.len                     # 4

Use UFCS where it reads naturally, and plain calls where it does not.

When designing a procedure that works "on" something, put that thing first. It will then read well in dotted form: list.append(item), text.wrapAt(80).

Stand-in: var parameters are pointers

C has no var keyword; the same effect uses a pointer. The caller must write &n explicitly, which, like Nim's rule, makes mutation visible at the call site.

C Stand-in: a var parameter as a pointer

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.

Stand-in: overloading with _Generic

C11 can select code by argument type at compile time with _Generic, which is close in spirit to overloading.

C Stand-in: compile-time overload selection

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 both languages the choice is made by the compiler, so nothing is decided while the program runs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you let a procedure modify the caller's variable?

    A var parameter is passed by reference; the caller must pass a mutable variable.
  2. 2. What is x.f(y) equivalent to?

    Uniform Function Call Syntax places the first argument before the dot.
  3. 3. Which parameter type accepts both an array and a seq of ints without copying?

    openArray[T] is a view over any contiguous list.
  4. 4. When is an overloaded procedure chosen?

    Overload resolution happens at compile time.

Summary

  • Ordinary parameters are read-only; var parameters let a procedure change the caller's variable.
  • openArray[T] and varargs[T] handle lists of arguments.
  • Procedures can be overloaded; the compiler picks the best match at compile time.
  • UFCS makes x.f(y) the same as f(x, y), allowing method-like chains.

Next: Iterators and closures