mirror of
https://github.com/nim-lang/Nim.git
synced 2026-01-04 04:02:41 +00:00
manual: more precise rules about evaluation order
This commit is contained in:
@@ -721,6 +721,44 @@ Rationale: Consistency with overloaded assignment or assignment-like operations,
|
||||
``a = b`` can be read as ``performSomeCopy(a, b)``.
|
||||
|
||||
|
||||
However, the concept of "order of evaluation" is only applicable after the code
|
||||
was normalized: The normalization involves template expansions and argument
|
||||
reorderings that have been passed to named parameters:
|
||||
|
||||
.. code-block:: nim
|
||||
:test: "nim c $1"
|
||||
|
||||
var s = ""
|
||||
|
||||
proc p(): int =
|
||||
s.add "p"
|
||||
result = 5
|
||||
|
||||
proc q(): int =
|
||||
s.add "q"
|
||||
result = 3
|
||||
|
||||
# Evaluation order is 'b' before 'a' due to template
|
||||
# expansion's semantics.
|
||||
template swapArgs(a, b): untyped =
|
||||
b + a
|
||||
|
||||
doAssert swapArgs(p() + q(), q() - p()) == 6
|
||||
doAssert s == "qppq"
|
||||
|
||||
# Evaluation order is not influenced by named parameters:
|
||||
proc construct(first, second: int) =
|
||||
discard
|
||||
|
||||
# 'p' is evaluated before 'q'!
|
||||
construct(second = q(), first = p())
|
||||
|
||||
doAssert s == "qppqpq"
|
||||
|
||||
|
||||
Rationale: This is far easier to implement than hypothetical alternatives.
|
||||
|
||||
|
||||
Constants and Constant Expressions
|
||||
==================================
|
||||
|
||||
|
||||
Reference in New Issue
Block a user