请在这里澄清左值和右值的概念

Please clarify the concept of lvalue and rvalue here

本文关键字:在这里      更新时间:2023-10-16

我有下面给出的程序

#include<stdio.h>
int main()
{
   int i=5;
   (++(++i));
}

这个程序在c++中可以很好地编译,但在c中不行。我也不能真正理解。但是我试着阅读和搜索,发现这是因为预增量运算符返回c中的右值和c++中的左值。

如果我将(++(++i))更改为(++(i++)),那么在c和c++中编译都会失败,因为后增量总是返回右值。

即使读了一些,我也不清楚这里的左值和右值到底是什么意思。谁能用外行的话解释一下这些是什么?

在c中,后缀或前缀++操作符要求操作数为可修改的左值。这两个操作符都执行左值转换,因此该对象不再是左值。

c++还要求前缀++操作符的操作数是一个可修改的左值,但前缀++操作符的结果是一个左值。对于后缀++操作符,情况并非如此。

因此,(++(++i));编译为第二个操作获得左值,但(++(i++))没有。

"左值(定位器值)表示一个对象占用内存中某个可识别的位置(即有一个地址)。

右值是通过排斥定义的,即每个表达式要么是左值,要么是右值。因此,从左值的上述定义来看,右值是一个表达式,它不表示占用内存中某个可识别位置的对象。"

参考:http://eli.thegreenplace.net/2011/12/15/understanding-lvalues-and-rvalues-in-c-and-c

根据这个定义,后增量i++将不再工作,因为返回的表达式不再位于i中,因为它是递增的。

同时,++i返回的表达式返回一个对变量i的引用

右值本质上是原始值或操作的临时结果,不应该对其进行操作。因此,不允许对这些对象进行自增前或自增后操作。

左值是指存储对象、函数或原语的传统值,可以对其进行操作或调用。

第一行:int i=5; // i is an lvalue, 5 is an rvalue

因此,++(i++)正在转换为++6,这实际上是编译器抱怨的问题。

顺便说一句,这里已经回答了:什么是右值,左值,左值,右值,右值和右值?

"lvalue" and "rvalue" are so named because of where each 
  of them can appear in an assignment operation.  An 
  lvalue 
 can appear on the left side of an assignment operator, 
  whereas an rvalue can appear on the right side.
  As an example:
int a;
a = 3;
In the second line, "a" is the lvalue, and "3" is the rvalue.
 in this example:

int a, b;
a = 4;
b = a;
In the third line of that example, "b" is the lvalue, and "a" is 
the rvalue, whereas it was the lvalue in line 2.  This 
illustrates an important point: An lvalue can also be an 
rvalue, but an rvalue can never be an lvalue.
Another definition of lvalue is "a place where a value can 
be stored."