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

Martin fpc at mfriebe.de
Tue Jul 3 20:06:49 CEST 2018


On 03/07/2018 19:27, Ondrej Pokorny wrote:
>> On 7/3/2018 9:40 AM, Ondrej Pokorny wrote:
>>> program Project1;
>>> var
>>>    S: string;
>>> begin
>>>    SetLength(S, 10); // <<< warning here --->> WHY ????
>>>    Writeln(S[2]);    // <<< no warning here --->> WHY ????
>>> end.
>>
>
> The compiler tells me that the line "SetLength(S, 10);" is potentially 
> dangerous, which it is not.
"writeln(a)" where a is "integer" is not >dangerous< either. Yet it is 
an uninitialized value that you write, and therefore likely not what you 
want (or you would have used random).
"potential error" <> "dangerous"

In any case,
- "S" is the array (the container, the length, and internally the 
pointer to the memory).
- SetLength is a function taking a "var param"

S has no specific value yet. So SetLenght gets a random value as param. 
Therefore this warning is correct.
To initialize "S":
    S := nil; // no warning

> The line "Writeln(S[2]);" is potentially dangerous, but the compiler 
> does not warn me about it.
It is a "potential error", dangerous or not.

I agree in a perfect world the compiler would keep track of each 
individual element in an array, and know which ones are initialized. In 
reality this doesn't work.

In theory there are 3 states that the compiler can have:
- it knows a variable is not initialized => It warns (even if the case 
it harmless)
- it knows a variable is initialized => it doesn't warn
- it doesn't know if a variable is initialized => it doesn't warn (and 
that is IMHO correct)

SetLength(S, 10); // The compiler knows S is not initialized
Writeln(S[2]);    // The compiler does not know (this is about S[2], not 
about S)

In the "s[2]" case, it could theoretically be implemented as a very 
special case. But the majority of array element access is not practical 
to implement.
And even in this case the cost/value is not balancing out.


> => The compiler warns me about the wrong line.
No, but it only gives you one out of 2 warnings.





More information about the fpc-devel mailing list