- 求值顺序
求值顺序
求值顺序是从左到右、从内到外,和大多数其他典型的命令式编程语言一样:
- var s = ""
- proc p(arg: int): int =
- s.add $arg
- result = arg
- discard p(p(1) + p(2))
- doAssert s == "123"
赋值也不例外,左侧表达式在右侧之前进行求值:
- var v = 0
- proc getI(): int =
- result = v
- inc v
- var a, b: array[0..2, int]
- proc someCopy(a: var int; b: int) = a = b
- a[getI()] = getI()
- doAssert a == [1, 0, 0]
- v = 0
- someCopy(b[getI()], getI())
- doAssert b == [1, 0, 0]
基本原理:与重载赋值或赋值类操作的一致性 a = b 可以读作 performSomeCopy(a, b).