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即擁有可讀屬性(可訪問)。app

等號左邊的表達式須要擁有lvalue,而等號右邊的表達式須要擁有rvalue。ide

相關文章
相關標籤/搜索