天天看点

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