c - foo(x++, y)::x 是否总是在作为参数发送后递增?

标签 c increment function-call

在涉及 x++ 的表达式的情况下,增量是否总是在要复制到函数的变量之后进行?

电话:

foo(x++, y);

函数:

int foo(int x, int y)
{
   return x*y;
}

这是所有编译器的未定义行为吗?

最佳答案

这里让我们看看官方的描述,加深理解。

对于后缀运算符,引用C11,章节§6.5.2.3

The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). [...] The value computation of the result is sequenced before the side effect of updating the stored value of the operand.

并且,关于函数调用,章节 §6.5.2.3

There is a sequence point after the evaluations of the function designator and the actual arguments but before the actual call. Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function.

因此,根据上面的描述,您的代码如上所示没有任何问题。

传递x的旧值,然后增加值。

但是,请注意第二个引用的最后部分,您需要保持代码的完整性。例如,您需要确保在中间没有序列点的情况下,值不会发生变化。有点像

 foo(x++, x++, y);

将是一个问题,因为您试图多次更改同一个变量 (x)。

关于c - foo(x++, y)::x 是否总是在作为参数发送后递增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47869497/

相关文章:

java - GAE 数据存储增量 ID

c - 如何在 C 中的 for 循环中访问 6 个不同的函数?

jquery 使用 .each() 递增数字

c - 增量比较截断

javascript - 如何在 React 组件中按顺序调用提取(A -> B -> C)?

python - 使方法返回 'self' 以链接方法调用是否好?

select() 后关闭套接字

c - 从nodejs中执行文件,写入它的stdin并将stdout管道传输到文件

将 32 位转换为浮点值

在没有 root 权限的情况下更改 Linux 中的网络设置