c - 函数参数中的逗号运算符

标签 c arguments expression comma-operator

我正在阅读 GNU C 手册的摘录:

You use the comma operator, to separate two (ostensibly related) expressions.

后面的描述:

If you want to use the comma operator in a function argument, you need to put parentheses around it. That’s because commas in a function argument list have a different meaning: they separate arguments.

到目前为止,一切都还好。奇怪的部分是:

foo (x, (y=47, x), z); is a function call with just three arguments. (The second argument is (y=47, x) .)

问题是:参数如何压入堆栈,如何从函数内部访问它?

最佳答案

就您而言,

  foo (x, (y=47, x), z);

功能类似于

  foo (x, x, z);

根据逗号运算符的属性,先计算左侧操作数并丢弃结果,然后计算右侧操作数,这就是结果。

为了完整起见,引用 C11 第 §6.5.17 章

The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

需要注意的是:变量 y 将被更新,因为 LHS 操作数被计算为 void 表达式,但对此函数调用没有影响。如果 y 是全局变量并在 foo() 函数中使用,它将看到初始值 47

也就是说,回答

how is the parameter pushed on the stack

非常依赖于实现(架构)。 C 没有指定函数参数传递的任何顺序,并且某些体系结构可能根本不使用“堆栈”进行函数参数传递!

关于c - 函数参数中的逗号运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46668680/

相关文章:

c - Linux 上使用 fpu_control.h 的 double

c++ - 使用模运算的正确方法

javascript - 如何在参数上使用 .reduce() 而不是特定的数组或对象?

sql - 如何使用 SSIS 派生列转换为 NULL 日期分配默认值?

c# - 处理 C# 表达式树中嵌套对象的空值

c++ - Sublime Text 启动单独的命令窗口(C/C++)

c - 全局数组或 "array"的 '#define' 的替代品?

JavaScript 对象 : Using Arguments as object property

events - 事件的行为,以及 Vue.js 中的 $event 变量

javascript 返回函数返回未定义