#include<stdio.h>
int swap(int *a,int *b);
int main()
{
int a=10,b=20;
swap(&a++,&b++);
printf("a=%d\nb=%d",a,b);
return 0;
}
int swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Why does this function give the error “invalid lvalue in unary ‘&'”?
Normal swap(&a,&b) works fine but swap(&a++,&b++) as well as swap(&(a++),&(b++)) give errors. What’s the reason behind this?
The post-increment operator returns a temporary version of the previous value contained in the variable on which the post-increment operation was performed. This temporary value is not a l-value, or “named” memory location, therefore you can’t take the address of that temporary using the unary address-of operator.
For instance, on certain architectures like x86, etc., a temporary value generated from the post-increment operator on a simple POD-type like a
int,longetc. will be temporarily held in a CPU register, not an actual memory location. In these instances you simply can’t take the “address” of a CPU register.