var a:array of integer;
i:integer;
begin
setlength(a,5);
i:=-1;
ifthen<integer>(i<0,0,a[i]);
end;
What this crap does?
By itself, as it is? Nothing, since you're not using or assigning IfThen's return value. As a side effect? If it doesn't bomb out with an exception at least you know
i is a valid index.
The question really is that, for all its "usefullnes", using
IfThen() to both check the index and access the array is a very bad idea. One should, instead, rely on an old and trusty
if ... then ... else ..., embedding it in a function if needed:
function NthElement(n: Integer; AnArray: TIntegerArray; DefVal: Integer): Integer;
begin
if (n >= Low(AnArray)) and (n <= High(AnArray)) then
Result := AnArray[n]
else
Result := DefVal;
end;
ETA: I forgot ...
Don't try to shorten the index check by testing just against
Length(AnArray).
Zero (0) is usually a valid index but it's also the length of an empty array, so the result of code such as:
function TTestApp.NthElement(n: Integer; IntArr: TIntegerArray): Integer;
begin
if Length(IntArr) <= n then
Result := IntArr[n]
else
Result := 0;
end;
procedure TTestApp.DoRun;
begin
Writeln('Array Length: ', Length(AnArray),
LineEnding,
'Element 0 : ', NthElement(0, AnArray));
Terminate;
end;
is, as should be expected:
Array Length: 0
Element 0 : Exception at 080480E0: EAccessViolation:
Access violation.