[英]delphi 7 function result can be undefined
I wrote this function wich compares string and return TRUE if it matches and FALSE if it doesn't. 我写了一个比较字符串的函数,如果匹配则返回TRUE,否则返回FALSE。
The only problem is that when I compile, I get an error saying that the result can be undefined. 唯一的问题是,当我进行编译时,出现一条错误消息,指出结果可能是不确定的。 I know this is not a problem as there are only 2 possible outcome in this particular situation but I'm kind of a perfectionnist and I want to get better.
我知道这不是问题,因为在这种特定情况下只有两种可能的结果,但是我是一个完美主义者,我想变得更好。 Can any of you enlighten me?
你们能启发我吗?
function filterUPC(upc: String): Boolean;
var
i, pos1: integer;
Plano: TStringList;
upcPlano: String;
begin
Plano := TStringList.Create;
if (fmMain.lblPlanook.Visible) and
not (fmMain.lblPlanook.Caption = 'INCOMPATIBLE') then
begin
Plano.LoadFromFile(fmMain.ebPlano.Text);
for i := 0 to Plano.Count - 1 do
begin
pos1:=AnsiPos(';', Plano[i]);
upcPlano := AnsiMidStr(Plano[i], pos1 + 1, 12);
if (upc = upcPlano) then
begin
Result := TRUE;
Break;
end
else if (i = Plano.Count - 1) then
begin
Result := FALSE;
end;
end;
end
else
begin
Result := FALSE;
end;
Plano.Free;
end;
Your result is undefined if Plano
is empty. 如果
Plano
为空,则结果不确定。 In that case, the for-loop never executes and Result
is never set. 在这种情况下,永远不会执行for循环,也永远不会设置
Result
。
Also, you should really wrap the TStringList create/free in a try/finally (since you're a perfectionist ;) 另外,您应该真正将TStringList create / free包装在try / final中(因为您是完美主义者;)
Here's what I would do: 这就是我要做的:
function filterUPC(upc: String): Boolean;
var
i, pos1: integer;
Plano: TStringList;
upcPlano: String;
begin
Result := FALSE;
Plano := TStringList.Create;
try
if (fmMain.lblPlanook.Visible) and (fmMain.lblPlanook.Caption <> 'INCOMPATIBLE') then
begin
Plano.LoadFromFile(fmMain.ebPlano.Text);
for i := 0 to Plano.Count -1 do
begin
pos1 := AnsiPos(';', Plano[i]);
upcPlano := AnsiMidStr(Plano[i], pos1 + 1, 12);
if (upc = upcPlano) then
begin
Result := TRUE;
Break;
end;
end;
end
finally
Plano.Free;
end;
end;
I've added Result:=FALSE;
我添加了
Result:=FALSE;
to the top, and removed the else
checks. 到顶部,并删除了
else
检查。 The try/finally guarantees that Plano will be freed, even if an exception is raised. try / finally保证即使出现异常也可以释放Plano。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.