C/C++当中lvalue和rvalue

有时候会遇到 lvalue和 rvalue 的两个名词,,,一直以为l和r是left和right的意思,即两个名词是左值和右值的意思。今天特意查了下,算是释了下疑。

Definition: C and C++ have the notion of lvalues and rvalues associated with variables and constants(常量). The rvalue is the data value of the variable or constant,that is what information it contains. The "r" in rvalue can be thought of as "read" value. A variable also has an associated lvalue. The "l" in lvalue can be thought of as location, meaning that a variable has a location that data or information can be put into. This is contrasted with a constant. A constant has some data value, that is an rvalue. But, it cannot be written to. It does not have an lvalue.

Another view of these terms is that objects with an rvalue, namely a variable or a constant can appear on the right hand side of a statement. They have some data value that can be manipulated. Only objects with an lvalue, such as variable, can appear on the left hand side of a statement. An object must be addressable to store a value.

Here are two examples.

int x;

x = 5; // This is fine, 5 is an rvalue, x can be an lvalue.
5 = x; // This is illegal. A literal constant such as 5 is not addressable. It cannot be a lvalue.

不知道大家明白了没有,简单说,lvalue即拥有地址属性(可写,因为这个地址就意味着内存中的一段空间),rvalue即拥有可读属性(可访问)。

等号左边的表达式需要拥有lvalue,而等号右边的表达式需要拥有rvalue。

你可能感兴趣的:(c/c++,R-value,L-value)