跳到正文

科技·工程

函数参数的求值顺序

litjohn约 4 分钟
原文

这是 2025年12月21日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年12月21日
收录
2025年12月21日
更新
2026年11月22日
篇幅
约 4 分钟

版本

  1. v4当前
  2. v3
  3. v2
  4. v1

本文也可以在 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, 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:

C++
void foo(int x, int y) {
    cout << x << " " << y << "\n";
}

int counter() {
    static int x = 0;
    x++;
    return x;
}

int main() {
    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.