;
之前不允许else
在大多数情况下。
if ((input = 'y') or (input = 'Y')) then
begin
writeln ('blah blah');
end
else if ((input = 'n') or (input = 'N')) then
begin
writeln ('blah');
end
else
begin
writeln ('Input invalid!');
end;
将编译。
但是...更喜欢使用begin
... end
括号以避免复杂代码的误解if then else
声明。
像这样的东西会更好:
if ((input = 'y') or (input = 'Y')) then
begin
writeln('blah blah');
end
else
begin
if ((input = 'n') or (input = 'N')) then
begin
writeln('blah');
end
else
begin
writeln('Input invalid!');
end;
end;
第二个示例更容易阅读和理解,不是吗?
删除后该代码不起作用begin
and end
因为前面有一个分号else
。这将编译没有错误:
if ((input = 'y') or (input = 'Y')) then
writeln('blah blah')
else
begin
end;
Appended关于@lurker的评论
请看下面的例子,不带begin
... end
括号。
if expr1 then
DoSmth1
else if expr2 then
if expr3 then
DoSmth2
else
DoSmth3;//Under what conditions is it called?
这里看不清楚,如果DoSmth3
被召唤not (expr2)
or (expr2) and (not (expr3))
。尽管我们可以预测此示例中的编译器行为,但更复杂的代码没有begin
... end
容易出错并且难以阅读。请看下面的代码:
//behaviour 1
if expr1 then
DoSmth
else if expr2 then
begin
if expr3 then
DoSmth
end
else
DoSmth;
//behaviour 2
if expr1 then
DoSmth
else if expr2 then
begin
if expr3 then
DoSmth
else
DoSmth;
end;
现在代码的行为是显而易见的。