简体   繁体   English

为什么swap(&a ++,&b ++)给出错误“一元'&'中的无效左值”?

[英]Why swap(&a++,&b++) gives error “invalid lvalue in unary '&'”?

#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. 普通swap(&a,&b)可以正常工作,但是swap(&a++,&b++)以及swap(&(a++),&(b++))都会出错。 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. 该临时值不是l值或“命名”的内存位置,因此,您不能使用一元地址运算符获取该临时地址。

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 , long etc. will be temporarily held in a CPU register, not an actual memory location. 例如,在某些体系结构(例如x86等)上,由后增量运算符在诸如intlong等简单POD类型上生成的临时值将被临时保存在CPU寄存器中,而不是实际的存储位置中。 In these instances you simply can't take the "address" of a CPU register. 在这些情况下,您根本无法采用CPU寄存器的“地址”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM