1

My problem got simplified after a few days of tearing my hair out (left the important bits only, refer to my many edits for history), here it is:

showmessage('i='+inttostr(i));
for i in [2..5,8,11..13] do
showmessage('1');
showmessage('i='+inttostr(i));

this is placed in a unit in my program of random fiddling with delphi. I think I should note that non-continuous for-in loop ranges work in the program elsewhere (another unit). In total, I have two such non-continuous for-in loops in the same procedure, if I comment out one the other works fine, but if they're both in working condition at the same time, only the second one works, the first one behaves like described below.

First messagebox contains "i= random-number" as it's not initialized, not that it needs to be. Messagebox with "1" in it never appears. Second messagebox that appears has "i=14", meaning that the loop did trigger but didnt do anything? That's ridiculous, if not, I want two things if someone can enlighten me:

1) why is this happening?

2) how to fix it and avoid in the future?

4

2 回答 2

2
showmessage('i='+inttostr(i));

i此时,内存的随机内容恰好位于分配给 storage for 的位置i,因为您没有对其进行初始化。

for i in [2..5,8,11..13] do
  showmessage('1');
showmessage('i='+inttostr(i));

您的代码中还有其他内容。这在 Delphi XE2 中运行良好:

procedure TForm2.FormCreate(Sender: TObject);
var
  j: Integer;
begin
  Memo1.Clear;
  for j in [2..5,8,11..13] do
    Memo1.Lines.Add(Format('j = %d', [j]));
end;

这是来自的输出Memo1

循环的示例输出

您的所有编辑和剩余噪音都非常混乱,您现在说要忽略,很难看出问题可能是什么;你有被剪掉的代码,你正在访问的未声明的变量,以及奇怪的逻辑(无论如何,从你所包含的内容来看)对我来说有任何意义。

不过,我认为您在这方面花费了太多时间,当一个非常简单的重写可以帮助您解决问题时(并且 IMO 将来更具可读性和可维护性,但这只是 IMO):

for i := 2 to 13 do
  case i of
    2..5, 8, 11..13:
      ShowMessage(Format('Got i value of %d', [i]));
    else:
      ShowMessage(Format('Got other value of %d', [i]));
  end;

就您在i另一个循环中看到从 50 到 1 的计数值而言,这是在调试器中查看循环计数器时的一个已知问题;它与混淆调试器评估器的代码优化有关。自 Delphi 1 以来,它一直是众所周知的(并且经常在 Borland/CodeGear/Embarcadero 新闻组中讨论)行为,并且仅影响调试器中的显示;保证不会影响代码实际执行结果的行为。

于 2012-01-09T23:02:47.227 回答
-1

您好,我在 Delphi 2006 和 Xe2 上测试了您的代码,在这两种情况下都运行良好;在我看来,可能有一个先前的问题可能会破坏内存,可能与变量或复选框数组有关;一旦我遇到这种情况(使用Delphi6),我必须在循环之前初始化J,我做了类似的事情:

procedure MyTestFunc();
var
i, j: integer;
begin
  memo1.lines.clear;
  for i:= 1 to 50 do
  Begin
    case i of
      1..10:
        if NOT (somearr[1] as Tcheckbox).checked then
        Begin
            j:=0;
            for j in [2..5,7,11..13] do
            begin
                memo1.Lines.Add('j= '+inttostr(j));
                (somearr[j] as Tcheckbox).Checked := false;
            end
        end
        else memo1.Lines.Add('false');
      11..20:BEgin
           End;
    End;
  End;
end;

我一直无法理解为什么会修复它。您始终可以逐步调试并检查每个变量。

如果您需要更多帮助,您可以发布更多代码,以便我们帮助您更好地解决此问题。

祝你好运!

于 2012-01-08T03:12:50.240 回答