我正在阅读 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/