[fpc-devel] Wrong docs: not initialized global variables

Ondrej Pokorny lazarus at kluug.net
Tue Jul 3 21:30:57 CEST 2018


On 03.07.2018 20:54, Florian Klämpfl wrote:
> The warning happens also for any other call which takes an 
> uninitialized variable as var parameter (see e.g. fillchar). So the 
> warning increases only orthogonality of the language. It was an 
> oversight that it not was thrown before.

This is correct in the oversimplified world only.

The not-oversimplified world is if the compiler was able to detect if 
the data in the VAR parameter is being read/used (and not initialized 
first) and emit a warning only for the methods that do read the data. 
This would both increase orthogonality of the warning (warning is not 
really the language, isn't it?) and it would be logical. E.g.:

program Project1;
type
   TMyArray = array[0..10] of Integer;
   procedure Init2(var A: TMyArray);
   begin
     A[2] := 1;
   end;
var
   A: TMyArray;
begin
   Init2(A);
end.

should not emit the warning because A is not being read in Init2.

IMPORTANT: the compiler knows that SetLength and FillChar don't read/use 
the data so no warning is appropriate there. Neither in FillChar, nor in 
SetLength.

---

What you achieved with SetLength and FillChar emitting a warning is that 
you made the compiler more stupid instead of making it more clever.

If you wanted to make the compiler clever, you would try to detect if 
the VAR parameter data is really being read/used and emit a warning only 
if you know it reads the data or when in doubt. IMO there are ways to 
detect if the VAR parameter is being read in a user-defined routine 
without initializing it there - they are similar to the ways that you 
use to detect an uninitialized local variable.

---

Furthermore from the programmer's point of view nothing can be more away 
from the purpose of the warning - both FillChar and SetLength.

The warning should warn me about potential errors in my code. Using 
SetLength or FillChar on an uninitialized variable is not and never can 
be a potential error. The compiler knows it because both SetLength and 
FillChar are compiler intrinsics. The compiler should be smart enough to 
know it and should not emit a warning in this case.

---

Btw. what I don't understand either: the above code (Init2(A);) and 
FillChar emit a hint only, SetLength emits a warning... It doesn't look 
orthogonal to me at all:

program Project1;
type
   TMyArray = array of Integer;
var
   A: TMyArray;
begin
   FillChar(A, 1, 0); // <<< HINT
end.

program Project1;
type
   TMyArray = array of Integer;
var
   A: TMyArray;
begin
   SetLength(A, 1); // <<< WARNING
end.


Ondrej



More information about the fpc-devel mailing list