程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> C和C++裡面的lvalue和rvalue的釋義

C和C++裡面的lvalue和rvalue的釋義

編輯:關於C++

在看GCC的文檔的時候,看到一個詞lvalue,查了金山詞霸其釋義為 lvalue [計] 左值。因為的確在介紹編譯原理的課程中聽過這個詞,大致知道其意思就沒有多想。但是看完GCC文檔的這個篇幅,都無法明白全篇在說什麼。問題還是出在了lvalue這個詞的“左值”是什麼意思的理解上了。再找M-W字典,卻告知沒有這個詞。於是google了一把,的確很多地方都稱其為左值,我仍然不得要領。最後在一個百科網站About Site上找到該詞的准確釋義,摘貼如下:

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, 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 though 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中的l其實指的表示該值的存儲地址屬性,而另外一個相對的詞rvalue值中的r指得是read的屬性,和左右根本沒有任何關系。金山詞霸的解釋真是狗屎啊。

作者的英文也是臭的可以, 自己沒有理解好原文, 自以為是, 就咬定這個錯, 那個錯了!

引文中說: "The "r" in rvalue can be thought of as "read" value."

就是你可以把 "r" 理解為 "read". 並沒有說就是 "read" 的意思!

其實, lvalue, rvalue 原來是怎麼說的, 恐怕也無從考證了. 不過, 稱為"左值", "右值" 並沒有違背原意. 因為, 到目前為止, 所有計算機語言都是將被賦值量置於賦值號左端的, 因此這種稱謂和理解非常直觀的. 對於賦值量來說, 也是相同的道理.

之所以有"location"和"read"的說法, 是因為在C/C++中, 有很多表達式是表達可賦值單元的, 我們不能簡單地理解"lvalue"就是變量. 如: a, *p, *(a->p+1), 等等. 這些都是C/C++的表達式, 不是變量, 故用"location"的含義可以避免很多誤解. 作者舉的例子:

5 = x;

許多人一看都能明白, 但卻不是問題的本質! 請看下面的例子:

 const int x;
  x = 1;  // 這裡 x 是 rvalue! 所以, 這是錯誤的賦值!
  struct fun {
   int a;
   int& operator()() { return a; }
   int& operator+(const fun& f) { return a+=f.a; }
   int operator-(const fun& f) { return a-f.a; }
  };
  fun f, g1, g2;
  f() = 1;  // 這裡 f() 是 lvalue! 所以, 這個賦值是正確的!
  g1 + g2 = 1;// 這裡 g1+g2 是 lvalue! 所以, 這個賦值是正確的!
  g1 - g2 = 1;// 這裡 g1-g2 是 rvalue! 所以, 這個賦值是錯誤的!

能夠理解這樣例子的同好, 顯然不難看出, lvalue 是叫"左值"(即: l 理解為 left)還是叫什麼別的(如: l 理解成location)根本就不是原則性的問題! 畢竟, 在計算機程序設計語言中, location 都是左置的!

至於, rvalue, 只不過是相對於 lvalue 而叫"右值"而已, 也並沒有什麼大不了的! 作者這麼咬文嚼字, 恐怕也會令 lvalue, rvalue 的首用者看了會啼笑皆非吧!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved