foo(x++, y) :: 在作为参数发送后 x 是否总是递增?
foo(x++, y) :: Does the x always incremented after to be send as argument?
涉及 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
)。
每当使用post增量时,变量的原始值将被发送到函数。之后,x的值将递增。
考虑以下程序
#include <stdio.h>
int x;
void foo(int x1 )
{
extern int x;
printf( "x1 = %d\n", x1 );
printf( "x = %d\n", x );
}
int main(void)
{
foo( x++ );
return 0;
}
它的输出是
x1 = 0
x = 1
由此可见表达式x++
的值是递增前操作数的值
x1 = 0
然而,副作用是在函数获得控制权之前应用的
x = 1
程序格式正确,没有未定义的行为。
涉及 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
)。
每当使用post增量时,变量的原始值将被发送到函数。之后,x的值将递增。
考虑以下程序
#include <stdio.h>
int x;
void foo(int x1 )
{
extern int x;
printf( "x1 = %d\n", x1 );
printf( "x = %d\n", x );
}
int main(void)
{
foo( x++ );
return 0;
}
它的输出是
x1 = 0
x = 1
由此可见表达式x++
的值是递增前操作数的值
x1 = 0
然而,副作用是在函数获得控制权之前应用的
x = 1
程序格式正确,没有未定义的行为。