我有以下代码:
#include <stdio.h>
int foo2(int *px, int *py)
{
int sum = *px + *py;
*px = *px + 1;
*py = *py - 1;
printf("foo2 : res=%d x=%d y=%d\n", sum, *px, *py);
return sum;
}
int main() {
int x = 4, y = 7, res;
res = foo2(&(x++), &(y--));
printf("%d", res);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我需要 increment x, decrement y,然后我需要将它们foo作为参数传递给函数。
我有error: lvalue required as unary ‘&’ operand。我也尝试使用x + 1andy - 1而不是x++and y++。
如何在函数调用中递增x和y值并传递指向它们的指针foo2?是否可以?
您可以使用逗号运算符:
res = foo2((x++, &x), (y--, &y));
Run Code Online (Sandbox Code Playgroud)
然而,这不是很可读,所以除非你有很好的理由,否则最好将它写成三个单独的语句:
x++;
y--;
res = foo2(&x, &y);
Run Code Online (Sandbox Code Playgroud)