I believe that local integer variables are not initialized to zero in delphi. The initial value is whatever happens to be at that memory location. So in the code below the first time the button is clicked the first message shows a integer value. How come the second time it's clicked it doesn't show 3 but instead shows the same integer value? It continues to show the same integer value each time I click the button. The value is different only when I stop and restart the program. Where is 3 being stored as it looks like the same memory location is used each time the button is clicked in the same run of the program?
procedure TForm1.Button1Click(Sender: TObject);
var
int1 : integer;
begin
showmessage(inttostr(int1)) ;
int1 := 3;
end;
end.
kjack,
It contains whatever value is in the stack frame at that time. In your case, this will be Sender. If you'd take the integer and typecast it to an object you'll notice the "pattern".
procedure TForm1.Button1Click(Sender: TObject);
var
int1 : integer;
begin
ShowMessage(TObject(int1).ClassName);
showmessage(inttostr(int1)) ;
int1 := 3;
end;
end.
Firstly, you're correct that local variables aren't initialised.
Also you can't guarantee that int1
is being stored in the same memory location on each invocation. In this case it could be that the reason you're seeing the same value each time is because it is using the same location (by chance) but the Delphi compiler has optimised away your final
int1 := 3;
statement as it has no effect. (You can add another showmessage(inttostr(int1))
call after that line and see if that makes a difference.) Another possibility is that the memory location used for int1
is reused between calls to your button handler (say in the Windows message loop) and that happens to always reset it to the value you're seeing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With