试图理解传递给函数的参数的求值(如果涉及一些算术运算)
Trying to understand the evaluation of parameters (if some arithmetic operations are involved) passed to a function
我试图理解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"
相关文章:
- 算术运算的结果类似于:C浮点变量中的1/3
- 更快的C++算术运算
- 为什么循环体中的一个基本算术运算执行得比两个算术运算慢
- 为什么对无符号字符进行算术运算会将它们提升为有符号整数
- 如何在 C++ 中计算字符串的算术运算
- 复数的算术运算
- 具有非常非常大数字的算术运算
- 如何使用C++中的处理器指令来实现快速算术运算
- boost::spirit::x3 phrase_parse 在进入 Vector 之前进行算术运算
- C++中混合数据类型的算术运算
- C++:编译器是否优化整数 + 浮点算术运算?
- 如何在特征中对二维数组的列执行简单的算术运算
- 使用数字列表和算术运算获取目标数字
- C++:“enable_if”用于限制支持特定算术运算的类型
- 如何正确避免 SIGFPE 和算术运算溢出
- 编译器用于编译 128 位整数的基本算术运算的技巧
- 将临时值存储为某种数据类型时,算术运算的标准规则是什么
- 相同的算术运算在 C++ 和 Python 中给出不同的结果
- 试图理解传递给函数的参数的求值(如果涉及一些算术运算)
- 如果算术运算的结果未存储在内存中会发生什么情况