Delphi/Pascal中if then begin end和;的正确结构语法

18

距离我上一次使用Pascal已经约20年了。我似乎无法正确地使用语言的结构元素,特别是在嵌套if then块时使用beginend。例如,这会让编译器报错,提示“需要标识符”("Identifier Expected")。

procedure InitializeWizard;
begin
  Log('Initialize Wizard');
  if IsAdminLoggedOn then begin
    SetupUserGroup();
    SomeOtherProcedure();
  else begin (*Identifier Expected*)
    Log('User is not an administrator.');
    msgbox('The current user is not administrator.', mbInformation, MB_OK);
    end  
  end;
end;

当然,如果我删除与它们相关的 if then 块和 begin end 块,那么一切都没问题。

有时候我能正确使用这种语法,并且结果也没问题,但是当嵌套 if then else 块时,问题会变得更加棘手。

仅仅解决问题还不够。我想要更好地理解如何使用这些块。显然我缺少某些概念。可能来自C++或C#的某些东西正在从我的思维的另一个部分渗入,并且破坏了我的理解力。我已经阅读了几篇相关文章,虽然我认为我理解了,但事实上并不是这样。


2
我不得不学习这种可怕的语言才能编写Inno Setup脚本。我的天啊。 - huang
那正是我正在做的事情! - amalgamate
那正是我正在做的事情! - undefined
1个回答

44

你需要将每个begin与同一层级的end匹配,就像这样:

if Condition then
begin
  DoSomething;
end
else
begin
  DoADifferentThing;
end;

如果您喜欢,可以缩短使用的行数而不影响排版。 (尽管在刚开始适应语法时可能会更容易使用以上方法。)

if Condition then begin
  DoSomething
end else begin
  DoADifferentThing;
end;

如果您只执行一个语句,则begin..end是可选的。请注意,第一个条件不包含终止符;,因为您尚未结束该语句:

if Condition then
  DoSomething
else
  DoADifferentThing;

在代码块的最后一个语句中,分号是可选的(尽管即使可选,我通常也会包括它,以避免未来添加一行并忘记同时更新前面一行时出现问题)。

if Condition then
begin
  DoSomething;            // Semicolon required here
  DoSomethingElse;        // Semicolon optional here
end;                      // Semicolon required here unless the
                          // next line is another 'end'.
您可以将单个和多个语句块结合在一起使用:
if Condition then
begin
  DoSomething;
  DoSomethingElse;
end
else
  DoADifferentThing;

if Condition then
  DoSomething
else
begin
  DoADifferentThing;
  DoAnotherDifferentThing;
end;

你的代码应该正确使用:

procedure InitializeWizard;
begin
  Log('Initialize Wizard');
  if IsAdminLoggedOn then 
  begin
    SetupUserGroup();
    SomeOtherProcedure();
  end 
  else 
  begin 
    Log('User is not an administrator.');
    msgbox('The current user is not administrator.', mbInformation, MB_OK);
  end;
end;

我错误地认为else块结束了begin块...我不知道我从哪里得到这个疯狂的想法。非常有帮助,谢谢。 - amalgamate
2
@amalgamate:如果你没有使用begin,那么你就不需要end。请参考我上面的第三个代码示例。 - Ken White
非常感谢,我认为这修复了我的大脑对该主题的正确状态。 - amalgamate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接