将For循环转换为不使用变量

时间:2015-11-22 04:40:14

标签: delphi for-loop delphi-xe7

我在我的应用中使用了很多虚拟树视图。为了构建节点,当我知道节点将有子节点时,我使用这个过程:

 VTV.BeginUpdate;
  VTV.Clear;
  for i := 0 to Length(vArray) - 1 do
  begin
    // Add a node to the root of the Tree
    if i = 0 then
    begin
      Node := VTV.AddChild(nil);
      Data := VTV.GetNodeData(Node);
    end
    else
    begin
      if vArray[i].Level = 0 then Node := VTV.AddChild(nil)
      else if vArray[i].Level > vArray[i - 1].Level then Node := VTV.AddChild(Node)
      else if vArray[i].Level < vArray[i - 1].Level then
      begin
        Node := Node.Parent;
        for j := 1 to (vArray[i - 1].Level - vArray[i].Level) do // line#: 428 warning: j not used!
          Node := Node.Parent;
        Node := VTV.AddChild(Node);
      end
      else
      begin
        Node := Node.Parent;
        Node := VTV.AddChild(Node);
      end;
      Data := VTV.GetNodeData(Node);
    end;
    // Create link to your data record into node
    Data.IndexInMyData := i;
    vArray[Data.IndexInMyData].NodePointer := Node;
  end;
  VTV.EndUpdate;

当我运行Peganza的Pascal Expert(Pascal Analyzer集成到IDE中)时,它给出了'for'循环中未使用'j'变量的消息:

[Pascal Expert] WARN42: Standards.pas(428): j For-loop variables not used in loop

我理解这条消息,并且在我使用'i'代替'j'等(来自复制粘贴代码)的其他情况下证明它是有用的,但在这种情况下不是。 由于我在许多虚拟树视图中使用相同的代码,因此我发生了很多此警告。

有任何建议我如何更改此For循环以便我不再收到此消息了吗?

for j := 1 to (vArray[i - 1].Level - vArray[i].Level) do
          Node := Node.Parent;

我希望我想要相同的长度或更短的时间,我不希望有这样的东西 - 这是太多的代码:

j:=1;
while j <= (vArray[i - 1].Level - vArray[i].Level) do
begin
  Node := Node.Parent;
  Inc(j);
end;

1 个答案:

答案 0 :(得分:4)

我认为没有办法以更清洁的方式编写代码。退一步,for循环有多种用途,但也许两个主要的用途如下:

  • 对集合的每个成员执行操作。
  • 执行N次动作。

这显然是一种简化,但如果你查看代码库中的for循环,你会发现它们总是属于一个类别或另一个类别。

现在,正在考虑的代码属于第二类。它是这种形式:

for I := 1 to N do
  Foo();

你怎么能写这个?您可以使用其他形式的循环,其中包含whilerepeat。正如您在while的情况下所观察到的那样,两者都不会产生更清晰的代码。另一种选择是使用递归实现来实现迭代。这不会更简单。

结论是你的静态分析工具拒绝一种常见且有效的迭代形式。问题不在于您的代码很弱,而是静态分析错误地诊断了不存在的问题。

解决方案:抑制或忽略这些特定的静态分析警告。

相关问题