Delphi Error – W1036 Variable ‘%s’ might not have been initialized

Delphi Compiler Error

W1036 Variable ‘%s’ might not have been initialized

Reason for the Error & Solution

This warning is given if a variable has not been assigned a value on every code path leading to a point where it is used.

program Produce;
(*$WARNINGS ON*)
var
  B: Boolean;
  C: (Red,Green,Blue);

procedure Simple;
var
  I : Integer;
begin
  Writeln(I);        (* <-- Warning here *)
end;

procedure IfStatement;
var
  I : Integer;
begin
  if B then
    I := 42;
  Writeln(I);        (* <-- Warning here *)
end;

procedure CaseStatement;
var
  I: Integer;
begin
  case C of
  Red..Blue: I := 42;
  end;
  Writeln(I);        (* <-- Warning here *)
end;

procedure TryStatement;
var
  I: Integer;
begin
  try
    I := 42;
  except
    Writeln('Should not get here!');
  end;
  Writeln(I);        (* <-- Warning here *)
end;

begin
  B := False;
end.

In an if statement, you have to make sure the variable is assigned in both branches. In a case statement, you need to add an else part to make sure the variable is assigned a value in every conceivable case. In a try-except construct, the compiler assumes that assignments in the try part may in fact not happen, even if they are at the very beginning of the try part and so simple that they cannot conceivably cause an exception.

program Solve;
(*$WARNINGS ON*)
var
  B: Boolean;
  C: (Red,Green,Blue);

procedure Simple;
var
  I : Integer;
begin
  I := 42;
  Writeln(I);
end;

procedure IfStatement;
var
  I : Integer;
begin
  if B then
    I := 42
  else
    I := 0;
  Writeln(I);        (* Need to assign I in the else part *)
end;

procedure CaseStatement;
var
  I: Integer;
begin
  case C of
  Red..Blue: I := 42;
  else       I := 0;
  end;
  Writeln(I);        (* Need to assign I in the else part *)
end;

procedure TryStatement;
var
  I: Integer;
begin
  I := 0;
  try
    I := 42;
  except
    Writeln('Should not get here!');
  end;
  Writeln(I);        (* Need to assign I before the try *)
end;

begin
  B := False;
end.

The solution is to either add assignments to the code paths where they were missing, or to add an assignment before a conditional statement or a try-except construct.