试图理解传递给函数的参数的求值(如果涉及一些算术运算)

Trying to understand the evaluation of parameters (if some arithmetic operations are involved) passed to a function

本文关键字:如果 算术运算 参数 函数      更新时间:2023-10-16

我试图理解cdecl调用约定,却偶然发现了这种奇怪的行为。

根据cdecl标准,调用函数将从右到左的参数存储到堆栈中,然后调用目标函数。因此,我假设参数将从左到右进行评估,因为这将类似于堆栈流,或者在给定用于存储参数的cdecl约定的情况下,它仍然可以从右到左进行评估。

但是下面程序的输出让我很困惑。下面是我写的一个简单的程序,用来理解参数的评估。

void fun (int a, int b, int c) {    
    printf("a: %d, b: %d, c: %dn", a, b, c);
}    
int main()    
{
    int i = 2; 
    fun(i, i++, i);
}  

预期输出:a: 3, b: 2, c: 2 or a: 2, b: 2, c: 3

实际输出:a: 3, b: 2, c: 3

 gcc --version
 gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2
 Copyright (C) 2013 Free Software Foundation, Inc.
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

有人能解释一下吗?

这是一个常见的混淆:有两个一元运算符递增一个数字:var++++var。在将变量的值传递给函数之后,var++将向变量添加一个,而++var将在将数据传递给函数之前添加一个。

尝试更改++运算符的位置,看看会发生什么。

快速示例:

#include <iostream>
int main() {
     int i = 5;
     std::cout << i << std::endl; //Prints "5"
     std::cout << i++ << std::endl; //Also prints "5", but after i is 6
     std::cout << ++i << std:: endl; //Prints "7"