On 03.07.2018 20:06, Martin wrote:
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.

You three (Ralf, Stefan and you) completely missed my point.

The warning and my point is not about array elements at all. Yes, I used an array element as an example but I could easily use the whole array/string in a different way, too.


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

No, the compiler warns me about the wrong line. SetLength/FillChar should not emit a warning at all because there is nothing to warn about. See my reply to Florian if my first email with the points was not clear enough.

Ondrej
_______________________________________________
fpc-devel maillist  -  fpc-devel@lists.freepascal.org
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-devel

Reply via email to