维基副本镜像

这是 pascal.chat 维基的镜像。编辑、历史记录和登录都在那里。

Basic Pascal Tutorial/Chapter 3/IF/zh CN

English · Français · Български · 中文(中国) · 日本語

3Ca - IF语句 (原作者: Tao Yue, 状态: 未更改)

IF 语句,计算表达式结果进行分支。单行格式为:

pascal
if ????????? then
  ??????;

如果表达式结果为真,则执行该语句,否则跳过。

IF 只接受一条语句;如果需要执行多条语句,则必须使用 begin-end:

pascal
if ????????? then
begin
  ??????1;
  ??????2
end;

当不满足条件时,还有一个选择:

pascal
if ????????? then
  ??????
else
  ??????;

表达式运算结果为假,则执行 else 后面的语句。 注意 else 前面没有分号,因为分号是两个语句之间的分隔符,而 else 并非语句。 如果在该处添了分号,则在编译的时候就会认为 if 语句到此结束,而把 else 当作另一句的开头。

如果有多个条件,只需要嵌套 if 语句:

pascal
if ??????1 then
  ??????1
else
  if ??????1 then
    ??????2
  else
    ??????3;

小心使用嵌套,程序运行结果可能不是你想要的。

pascal
if ??????1 then
  if ??????2 then
    ??????2
else
  ??????1;

else 总是匹配与它最近的 if:

pascal
if ??????1 then
  if ??????2 then
    ??????2
  else
    ??????1;

你可以使用空语句:

pascal
if ??????1 then
  if ??????2 then
    ??????2
  else
else
  ??????1;

或者你可以使用 begin-end,但代码整洁的最佳方法是将条件重写。

pascal
if not ??????1 then
  ??????1
else
  if ??????2 then
    ??????2;

如果表达式像这样:(not(a < b) or (c + 3 > 6)) and g,理解起来会很费劲。

仍需要注意,代码缩进便于阅读代码(编译器忽略缩进)。

上一页 目录 下一页

From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 3/IF/zh CN", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

版本1,最后由WikiArchive于修改。