天天看點

Pointers on C——6 Pointers.7

​6.7 Pointers, Indirection, and L-values

Can expressions involving pointers be used as L‐values? If so, which ones? A quick check of the precedence chart in Table 5.1 confirms that the operand needed by the indirection operator is an R‐value, but the operator produces an L‐value.Weʹll return to an earlier example. Given these declarations

指針變量可以作為左值,并不是因為它們是指針,而是因為它們是變量。對指針變量進行間接通路表示我們應該通路指針所指向的位置。間接通路指定了二個特定的記憶體位置,這樣我們可以把間接通路表達式的結果作為左值使用。在下面這兩條語句中,

int a;

int *d = &a;

consider the expressions below:

Pointers on C——6 Pointers.7

Pointer variables may be used as L‐values, not because they are pointers but because they are variables. Applying indirection to a pointer variable indicates that we should follow the pointer. The indirection identifies a specific memory location, thus we can use the result of an indirection expression as an L‐value. Follow these statements:

指針變量可以作為左值,并不是因為它們是指針,而是因為它們是變量。對指針變量進行間接通路表示我們應該通路指針所指向的位置。間接通路指定了一個特定的記憶體位置,這樣我們可以把間接通路表達式的結果作為左值使用。在下面這兩條語句中,

*d = 10 - *d;

d = 10 - *d; ← ???

The first statement contains two indirections. The expression on the right is being used as an R‐value, so it obtains the value in the location to which d points (the value of a).The indirection on the left is being used as an L‐value, so the location to which d points(which is a) receives the new value computed by the right side.

第1 條語句包含了兩個間接通路操作。右邊的間接通路作為右值使用,是以它的值是d 所指向的位置所存儲的值(a 的值)。左邊的間接通路作為左值使用,是以d 所指向的位置(a)把指派符右側的表達式的計算結果作為它的新值。

The second statement is illegal because it specifies that an integer quantity(10 - *d) be stored in a pointer variable. The compiler helps us out by complaining when we try to use a variable in a context that is inconsistent with its type. These warning and error messages are your friends. The compiler is helping  you by producing them. Although we would all prefer not to have to deal with any such messages, it is a good idea to correct the errors right away, especially with warning messages that do not abort the compilation. It is a lot easier to fix problems when the compiler tells you exactly where they are than it is to debug the program later; the debugger cannot pinpoint such problems nearly as well as the compiler.

第2 條語句是非法的,因為它表示把一個整型數量(10-*d)存儲于一個指針變量中。當我們實際使用的變量類型和應該使用的變量類型不一緻時,編譯器會發出抱怨,幫助我們判斷這種情況。這些警告和錯誤資訊是我們的朋友,編譯器通過産生這些資訊向我們提供幫助。盡管被迫處理這些資訊是我們很不情願幹的事情,但改正這些錯誤(尤其是那些不會中止編譯過程的警告資訊)确實是個好主意。在修正程式方面,讓編譯器告訴你哪裡錯了比你以後自己調試程式要友善得多。調試器無法像編譯器那樣準确地查明這些問題。

Old C compilers did not complain when pointer and integer values were intermixed.However, we know better these days. It is only rarely useful to convert an integer to a pointer or vice versa. Usually such conversions are unintentional errors.

K&RC:當混用指針和整型佳時,舊式C 編譯器并不會發出抱怨。但是,我們現在對這方面的知識知道得更透徹一些了。把整型值轉換為指針或把指針轉換成整型值是極為罕見的,通常這類轉換屬于無意識的錯誤。

上一章 Pointers on C——6 Pointers.6