正文
增加 40 行删除 13 行
1234567891011121314158 行未改动2425262728293031323334353637383940414243444546本文也可以在 <https://litjohn.pages.dev/posts/evaluation-order-of-function-arguments/> 观看。洛谷文章区就是我的垃圾桶!以及,中文导致遇到很多全站推荐格式问题。那么我不用中文了!You might assume that computers evaluate function arguments from left to right. However, that is not always the case.In fact, many programming languages—such as C++ and RnRS Scheme—leave the evaluation order of arguments unspecified.As shown in [this post](https://www.luogu.com.cn/discuss/1220027), ignoring this detail can trigger undefined behavior, leading to a Wrong Answer (WA) or Runtime Error (RE).Let’s break it down. Consider the following piece of code:```cppvoid foo(int x, int y) {cout << x << " " << y << "\n";}8 行未改动foo(counter(), counter());return 0;}```Compile and run it using GCC 15.2 with -O2 and -std=c++20 flags.You'll notice that the output is `2 1`.Or this scheme code snippet:```scheme(let ([x (read)][y (read)])(printf "~a ~a" x y))```will get a similar surprising result.The reason is that compilers choose to evaluate arguments from right to left.Why do the compilers do this? It's not a bug, but a deliberate trade-off in the language design. The standards leave the evaluation order unspecified to give the compiler more room for optimization. By sacrificing the intuitiveness of a strict left-to-right order, compilers can leverage instruction reordering and parallelization to squeeze out better performance.Another factor is the efficiency of calling conventions. In many x86 architectures, the stack grows downwards, and the rsp register points to the top of the stack. To ensure that the leftmost arguments are positioned closer to the top of the stack, the compiler often evaluates and pushes arguments from right to left. This arrangement simplifies how the callee accesses its parameters.This right-to-left order is crucial for variadic functions like `printf`, as it ensures the fixed arguments are always at a known position relative to the stack pointer.12345678910111213141516178 行未改动262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273本文也可以在 <https://litjohn.pages.dev/posts/evaluation-order-of-function-arguments/> 观看。中文导致遇到很多全站推荐格式问题。那么我不用中文了!You might assume that computers evaluate function arguments from left to right. However, that is not always the case.In fact, many programming languages—such as C++ and RnRS Scheme—leave the evaluation order of arguments **unspecified**.As shown in [this post](https://www.luogu.com.cn/discuss/1220027), ignoring this detail can trigger undefined behavior, leading to a Wrong Answer (WA) or Runtime Error (RE).### The Behavior in C++ and SchemeConsider the following C++ code:```cppvoid foo(int x, int y) {cout << x << " " << y << "\n";}8 行未改动foo(counter(), counter());return 0;}```If you compile and run this using GCC 15.2 with `-O2`, you might notice the output is `2 1`. The compiler chose to evaluate the arguments from right to left.Similarly, in Scheme:```scheme(let ([x (read)][y (read)])(display x) (display " ") (display y))```If you type `A` then `B` into the console, you might find `y` gets `A` and `x` gets `B`, because the order in which `(read)` is called for each binding is unspecified.### Why the Ambiguity?This is not a bug, but a deliberate trade-off. Standards leave the order unspecified to grant compilers freedom for optimization. By not forcing a strict left-to-right order, compilers can better leverage instruction reordering, register allocation, and parallelization.In older x86 C environments, evaluating from right to left was also a matter of efficiency. Since the stack grows downwards, pushing arguments from right to left ensures the leftmost argument ends up at the "top" of the stack, simplifying how functions like `printf` locate their first fixed argument.### Precise Semantics: C++17 and SchemeIn C++ (pre-C++17), these evaluations were *unsequenced*. Modifying the same object twice resulted in **Undefined Behavior (UB)**. Since C++17, they are *indeterminately sequenced*—the result is **unspecified**, but the behavior is no longer "undefined" (no nasal demons).The RnRS Scheme standard goes a step further, stating:> "When a procedure call is evaluated, the **operator and operand expressions are evaluated (in an unspecified order)** and the resulting procedure is passed the resulting arguments."This means even the function itself (the operator) could be evaluated *after* its arguments.### The "Nesting" Escape Hatch: Why `let*` Still WorksIf the order is so chaotic, you might wonder: **How can Scheme implement `let*` (which guarantees sequential binding) if it's just "syntactic sugar" for nested lambdas?**The answer lies in the distinction between **evaluation order within a call** and **the execution flow of a closure**.A `let*` expression:```scheme(let* ([x 1] [y (+ x 1)]) body)```expands into nested lambdas:```scheme((lambda (x)((lambda (y) body) (+ x 1)))1)```In this nested structure, the inner expression `(+ x 1)` is part of the **body** of the outer lambda. According to Scheme semantics, the body of a procedure can only begin execution **after** the procedure has been called and its arguments have been fully evaluated.Even if the compiler evaluates the outer operator (`lambda (x)...`) after the outer operand (`1`), the *inner* call cannot even be "seen" by the evaluator until the outer call happens. **Nesting transforms a "horizontal" ordering problem (where order is unspecified) into a "vertical" dependency (where order is guaranteed by the flow of data).**### ConclusionWhen writing code that relies on side effects (like `read`, `set!`, or `counter++`), never assume a left-to-right order unless the language explicitly guarantees it (like Java or Python). If you need a specific sequence in Scheme or C++, use explicit sequencing constructs like `let*`, `begin`, or separate statements to ensure your code remains portable and predictable.