I have the following code:
#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;
}
I need to increment x
, decrement y
, then I need to pass them in foo
function as arguments.
I have error: lvalue required as unary '&' operand
. Also I tried to use x + 1
and y - 1
instead of x++
and y++
.
How can I increment x
and y
values and pass pointer to them in foo2
function call? Is it possible?
You can use the comma operator:
res = foo2((x++, &x), (y--, &y));
However this is not very readable, so unless you have a really good reason it is better to write it as three separate statements:
x++;
y--;
res = foo2(&x, &y);
I just want to add some points here:
C :
In c both the prefix and postfix increment returns the rvalue
. So that's the reason you will get an error when you try to get address of post/pre-increment in c.
C++ :
But in c++, the prefix (++x)
returns lvalue
and postfix(x++)
returns a rvalue
. So in c++, &(++x)
is correct whereas &(x++)
throws the error.
Note:
I encourage you to read about this a bit more. It will help you a lot to understand much better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.