Lead to simple code when variables are not initialized

Today, one of my friends asks me about the code below:

var a: Integer; begin ShowMessage(IntToStr(a)); end; 

This is a local variable and has not been initialized, ok?

Put the code in the OnClick event of the button component, and then run the code in three different ways:

  • Press the button and look at the result, result = 1635841
  • Press Enter and you will see the result, the result = 1
  • Press the spacebar and see the result, reuslt = 1636097

I am testing the code on two different computers and see the same result, any idea about this?

+6
source share
3 answers

Since the variable is not initialized, its value can be any. Since your result is โ€œsomething,โ€ there is nothing unusual here.

+10
source
 procedure TForm1.Button1Click(Sender: TObject); var a: Integer; begin ShowMessage(IntToStr(Integer(a))); end; procedure TForm1.Button2Click(Sender: TObject); begin ShowMessage(IntToStr(Integer(Pointer(TButtonControl(Button1))))); end; 

on my machine, this code generates the same message that the compiler uses ebx for variable a , and TButtonControl.WndProc uses ebx to save a pointer to Self (since EAX will be overwritten after calling the WinAPI function from TbuttonControl.WndProc), which is button1 , before calling the actual Button1Click handler. So alas, in Delphi 2007 the message text is too predictable.

[edit] You can see what happens inside the VCL when debugging, if you enable the Use debug DCUs option in the project compiler options Compiler-> Debugging-> Use debugging DCUs .

+2
source

See this similar fooobar.com/questions/66462 / ....

In Delphi, local variables are not initialized by default. The programmer is responsible for this, and he must always set the value before reading it. The value of a unified variable depends on the contents of the actually allocated memory cells used for this variable. Therefore, any value is possible here.

+1
source

Source: https://habr.com/ru/post/893414/


All Articles