If you don't explicitly initialize a global variable, the compiler initializes it to 0. Object instance data (fields) are also initialized to 0. On the Wiin32 platform, the contents of a local variable are undefined until a value is assigned to them.
所以只有局部變量的值需要程序員設定, AutoSize是TControl的Object instance data - FAutoSize, 所以它一定會被compiler初設為0(False).
--------------------------------------------------------------------------------
autosize是類里面的字段
類實例在初始時,會自動fillchar。
var
A: Boolean
是棧變量,臨時性,隨機性是棧變是的特性。
--------------------------------------------------------------------------------
參考:
ms-help://borland.bds4/bds4ref/html/Variables.htm
http://docwiki.embarcadero.com/RADStudio/XE8/en/Variables
--------------------------------------------------------------------------------
另外,Delphi會優化布爾表達式:
function TControl.CheckNewSize(var NewWidth, NewHeight: Integer): Boolean; var W, H, W2, H2: Integer; begin Result := False; W := NewWidth; // cx H := NewHeight; // cy if DoCanResize(W, H) then // 類函數,給程序員控制的機會,然后再繼續傳遞。程序員要求限制,才進行限制 begin W2 := W; H2 := H; Result := not AutoSize // 通常情況下下AutoSize=false,這樣Result就已經等於true or (DoCanAutoSize(W2, H2) and (W2 = W) and (H2 = H)) // 問題: 編譯器優化的話,還會執行這個函數嗎? or DoCanResize(W2, H2); // 這個函數也是如此 if Result then begin NewWidth := W2; NewHeight := H2; end; end; end;
我覺得上面的代碼是故意為之:
Result := not AutoSize
or (DoCanAutoSize(W2, H2) and (W2 = W) and (H2 = H))
or DoCanResize(W2, H2);
也就是說,當autoSize=false的時候,就不用執行后面的函數了。只有autoSize=true的時候,才需要執行函數。而現實正是:只有控件運行自動擴展大小的時候,才需要執行后面的函數做進一步檢查。
結論:Delphi編譯器會優化布爾表達式。1樓的代碼之所以這樣寫,是故意為之,正好符合現實的需求。這樣寫雖然容易迷惑,但也可認為是VCL創作人員的高超的技巧性。
參考:http://bbs.2ccc.com/topic.asp?topicid=496677
