天天看點

Pointers on C——6 Pointers.8

​6.8 Pointers, Indirection, and Variables

If you think youʹve mastered pointers, take a look at this expression and see if you can figure out what it does

如果你自以為己經精通了指針,請看一下這個表達式,看看你是否明白它的意思。

*&a = 25;

If you said that it assigns the value 25 to the variable a, congratulations— youʹre right.Letʹs unravel the expression. First, the & operator generates the address where the variable a is stored, which is a pointer constant. (Note that it is not necessary to know the actual value of the constant in order to use it.) Then, the * operator goes to the location whose address is given as the operand. In this expression, the operand is the address of a, so the value 25 is stored in a.

如果你的答案是它把值25 指派給變量a,恭喜!你答對了。讓我們來分析這個表達式。首先,&操作符産生變量a 的位址,它是一個指針常量(注意,使用這個指針常量并不需要知道它的實際值)。接着,*操作符通路其操作數所表示的位址。在這個表達式中,操作數是a 的位址,是以值25就存儲于a 中。

How is this statement any different from just saying a =25; ? Functionally, it is identical. It does, however, involve more operations. Unless the compiler (or optimizer) realizes what youʹre doing and discards the extra operations, the resulting object code will be larger and slower. Worse, the additional operators make the source code harder to read. For these reasons, no one ever (intentionally) uses expressions such as *&a.

這條語句和簡單地使用a=25;有什麼差別嗎?從功能上說,它們是相同的。但是,它涉及更多的操作。除非編譯器(或優化器)知道你在幹什麼并丢棄額外的操作,否則它所産生的目标代碼将會更大、更慢。更糟的是,這些額外的操作符會使源代碼的可讀性變差。基于這些原因,沒人會故意使用像*&a 這樣的表達式。

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