函数参数中的逗号运算符
The comma operator in a function argument
我正在阅读 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);
按照逗号运算符的属性,计算LHS操作数并丢弃结果,然后计算RHS操作数,这就是结果。
为完成起见,引用 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 没有为函数参数传递指定任何顺序,并且某些体系结构可能根本不使用 "stack" 进行函数参数传递!
我正在阅读 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);
按照逗号运算符的属性,计算LHS操作数并丢弃结果,然后计算RHS操作数,这就是结果。
为完成起见,引用 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 没有为函数参数传递指定任何顺序,并且某些体系结构可能根本不使用 "stack" 进行函数参数传递!