Do I need to 'create'/initialize local variables if they are just used as pointers to form controls?

122 views Asked by At

I have this simple example of syncing Scrollboxes, where I control which side is synced by Radio button - Sync Left or Right side. When I compile, I get compiler messages:

[dcc32 Warning] Unit1.pas(51): W1036 Variable 'ScrlBox1' might not have been initialized

[dcc32 Warning] Unit1.pas(51): W1036 Variable 'ScrlBox2' might not have been initialized

This is the simple example:

procedure TForm1.Button1Click(Sender: TObject);
var
  ScrlBox1, ScrlBox2: TScrollBox;
begin

    if radiobtn_SyncLeftSides.Checked then // Snyc Left side
    begin
      ScrlBox1 := ScrollBoxLeft1;
      ScrlBox2 := ScrollBoxLeft2;
    end
    else if radiobtn_SyncrightSides.Checked then  // Snyc Right side
    begin
      ScrlBox2 := ScrollBoxRight1;
      ScrlBox1 := ScrollBoxRight2;
    end;

    // Sync scroll boxes
    ScrlBox2.VertScrollBar.Position := ScrlBox1.VertScrollBar.Position;
    ScrlBox2.HorzScrollBar.Position := ScrlBox1.HorzScrollBar.Position;

end;

What is the issue here?

If I add this at the beginning the message is gone:

ScrlBox1:= TScrollBox.Create(nil);
ScrlBox2:= TScrollBox.Create(nil);

but I don't think creating scroll box variables is necessary, right? These are just variable pointers to controls on form.

1

There are 1 answers

8
Remy Lebeau On BEST ANSWER

If both radiobtn_SyncLeftSides and radiobtn_SyncrightSides are unchecked, you are not initializing the ScrlBox1 and ScrlBox2 variables before using them. That is what the compiler is complaining about.

procedure TForm1.Button1Click(Sender: TObject);
var
  ScrlBox1, ScrlBox2: TScrollBox;
begin
  if radiobtn_SyncLeftSides.Checked then // Snyc Left side
  begin
    ScrlBox1 := ScrollBoxLeft1;
    ScrlBox2 := ScrollBoxLeft2;
  end
  else if radiobtn_SyncrightSides.Checked then  // Snyc Right side
  begin
    ScrlBox2 := ScrollBoxRight1;
    ScrlBox1 := ScrollBoxRight2;
  end else
  begin
    // NOT INITIALIZED HERE!!!!!
  end;

  // Sync scroll boxes
  ScrlBox2.VertScrollBar.Position := ScrlBox1.VertScrollBar.Position;
  ScrlBox2.HorzScrollBar.Position := ScrlBox1.HorzScrollBar.Position;
end;

If you don't want to sync the scrolling, you should just Exit the procedure:

procedure TForm1.Button1Click(Sender: TObject);
var
  ScrlBox1, ScrlBox2: TScrollBox;
begin
  if radiobtn_SyncLeftSides.Checked then // Snyc Left side
  begin
    ScrlBox1 := ScrollBoxLeft1;
    ScrlBox2 := ScrollBoxLeft2;
  end
  else if radiobtn_SyncrightSides.Checked then  // Snyc Right side
  begin
    ScrlBox2 := ScrollBoxRight1;
    ScrlBox1 := ScrollBoxRight2;
  end else
  begin
    Exit; // <-- HERE
  end;

  // Sync scroll boxes
  ScrlBox2.VertScrollBar.Position := ScrlBox1.VertScrollBar.Position;
  ScrlBox2.HorzScrollBar.Position := ScrlBox1.HorzScrollBar.Position;
end;