Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Delphi 6 warn variable "i" may not have been initialized?

Optimization on/off doesn't matter. This is simplified code to demonstrate the warning. In the original routine all assignments and compares are to function expressions that could return a variety of values.

procedure test;
var i, k: integer;
begin
k := 21;
repeat
  if k = 20 then break;
  i := 5
until i = 5;
end;
like image 400
Witness Protection ID 44583292 Avatar asked Sep 18 '14 04:09

Witness Protection ID 44583292


1 Answers

This does seem to be a weakness in the compiler.

repeat
  if k = 20 then break;
  i := 5
until i = 5;

A human static analysis can easily check that i is always assigned before it is read. The line before the until assigns it. If that assignment is skipped by the break, then the until test is also skipped.

So, this can only be described as a compiler bug because the compiler should be able to understand how break and until interact. Clearly the compiler's analysis depends on an understanding of these things, since removing the break will also remove the warning. So it can only be that the compiler doesn't understand well enough.

It turns out that the 32 bit Windows compiler still behaves the same way in the current Delphi release, XE7. But the 64 bit compiler correctly emits no warning for your code.

Note that you might expect the compiler to realise that the condition in the if test in your code always evaluates False. Well, the compiler won't. It does not perform static analysis of constant propagation through non constant variables. Its analysis takes no account of the values that you place in variables.

like image 103
David Heffernan Avatar answered Sep 17 '22 08:09

David Heffernan