Type Switch
Syntax {$J+} or {$J-}
{$WRITEABLECONST ON} or {$WRITEABLECONST OFF}
Default {$J+}
{$WRITEABLECONST ON}
Scope Local
The $J directive controls whether typed constants can be modified or not. In the {$J+} state, typed constants can be modified, and are in essence initialized variables. In the {$J-} state, typed constants are truly constant, and any attempt to modify a typed constant causes the compiler to report an error.
In previous versions of Delphi and Borland Pascal, typed constants were always writeable, corresponding to the {$J+} state. Old source code that uses writeable typed constants must be compiled in the {$J+} state, but for new applications it is recommended that you use initialized variables and compile your code in the {$J-} state.
In the default {$J+} compiler state, typed constants can have new values assigned to them; they behave essentially like initialized variables. But if the {$J-} compiler directive is in effect, typed constants cannot change value at runtime; they are, in effect, read-only variables.
type
TForm1 = class(TForm)
procedure FormPaint(Sender: TObject);
private
{ Private declarations }
procedure WMPowerBroadcast(var message: TMessage); message WM_POWERBROADCAST;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
{ TForm1 }
procedure TForm1.WMPowerBroadcast(var message: TMessage);
{$J+} //我加了这句后,D6下就对了!
const SkipNextPowerMsg:boolean=True; //这句在D6下出错!
//另外,请大家分析一下,上面的这句定义是不是类似C++中的Static 局部变量??
begin
if SkipNextPowerMsg then
begin
SetForegroundWindow(Self.Handle);
if Application.MessageBox('是否关闭系统?','警告',MB_OKCANCEL + MB_DEFBUTTON2)<>IDOK then
begin
message.Result := BROADCAST_QUERY_DENY;
SkipNextPowerMsg:=not SkipNextPowerMsg;
end
else
Close;
end
else
SkipNextPowerMsg:=not SkipNextPowerMsg;
end;
procedure TForm1.FormPaint(Sender: TObject);
begin
Self.Visible:=False;
end;
是的,只有全局变量才可以被初始化。下面是我在Borland新闻组上的帖子和一个老外的回帖。
----------------------
"Rannce" <Rannce@21cn.com> wrote:
> {$J+} compiler state is default in D5, and it's changed to {$J-}
> is the default state in D6?
Correct. The default has changed.
--
Dave Nottage
-----------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
begin
i:= 10 ; //D6下,在这一句出错 。D5下没错。
ShowMessage(IntTostr(i));
end;
改成:
----------------------------------------------------
var
Form1: TForm1;
var
i:integer=0;
procedure TForm1.Button1Click(Sender: TObject);
begin
i := 10; //no problem
ShowMessage(IntTostr(i));
end;
或者:
-----------------------------
var
Form1: TForm1;
{$J+}
const
i:integer=0;
procedure TForm1.Button1Click(Sender: TObject);
begin
i := 10; //no problem
ShowMessage(IntTostr(i));
end;