1. Computing

Be Aware Of Uninitialized Variables

Ignoring the "Variable 'btn' might not have been initialized" Warning? Do NOT!

By

Article expired by a thread in public newsgroup.

Take a look at your Delphi application, the one you are developing for many days (weeks, years) ... when you hit "Compile" - how many compiler warnings do you see? Zero? Bravo! A few? A dozen, hundreds?

The more complex (more code) the application, the more warnings you can get from the Delphi compiler. Are you certain that you understand what the Compiler is trying to tell you? Are you making sure to fix the code so that no warnings are reported?

For me, I have to confess: there are some types of warnings that I'm ignoring :(

I do know what a warning "Variable 'btn' is declared but never used in 'mybuttons'" or "Return value of function 'MyFunctionDontCareAboutTheResult' might be undefined" mean. I can live with those warnings.

But, there are some warnings you should never take for granted!

What happens when you are ignoring 10-50 warnings "on purpose" and there's one (or more) warning you fail to see in the Build-Messages window?

[DCC Warning] W1036 "Variable 'btn' might not have been initialized"

Take a look at the following code block:
//handles Form's OnCreate event
procedure TMainForm.FormCreate(Sender: TObject);
var
  btn : TButton;
begin
  btn.Caption := 'button or form caption!?';
end;
There's a variable of type "TButton" named "btn". There's an assignment to btn's Caption property in the OnCreate event handler of a form.

Compile. 1 warning: "Variable 'btn' might not have been initialized". C'mon, who reads those warnings? If it is not an error (meaning you *can* compile and run) - you run.

What's the result when you run the code? An access violation? Yes, if you are lucky ;)

The result (in Delphi 2007) would be that the form's caption has changed to "'button or form caption" - didn't expect that, did you?

Nasty, Nasty Pointers!

What's "btn" in the above code? "Btn" is a variable of a type TButton - actually a pointer that references an object. "Btn", as the warning warns has not been initialized. Since "btn" has not been initialized (to at least "nil"), the value of "btn" will be a random memory location.

In this particular case, this random location is where the pointer to the form's variable is.
Setting uninitialized btn's Caption results in setting the Caption of the form!

A non-initialized variable is pointing to nowhere, or to be precise it does point to somewhere, and the results of using such a variable can be unpredictably dangerous.

Warnings Are NOT Errors BUT Treat 'Em As Such

Already compiling your Delphi application to see how many warnings are there that you have been marking as "never mind"? I am ;)
  1. About.com
  2. Computing
  3. Delphi
  4. Coding Delphi Applications
  5. Be Aware Of Uninitialized Variables - Always Ensure your Delphi Objects ARE Initialized

©2014 About.com. All rights reserved.