Sign in Join
Wiki copytemporary

Basic Pascal Tutorial/Chapter 3/IF/zh CN

Sent here from 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.

Revision 1, last changed by WikiArchive .

Edited on wiki.freepascal.org by 5 people, 2013–2022

From the official wiki's backup of 26 May 2024: who edited this page there, and when. Edits made there after that date were not recorded, and the earlier versions are not shown here; the main page says why.

WhenWhoWhat changed
WangyouworldCreated page
Wangyouworld
Swen (minor)
Wangyouworld (minor)
FTurtle
TrevFixed syntax highlighting (minor)
Kai BurghardtKai Burghardt moved page IF/zh CN to Basic Pascal Tutorial/Chapter 3/IF/zh CN: tidy up main name space: create subpage hierarchy for basic Pascal tutorial [cf. [[Special: PermaLink/149778#Clutterin... (minor)
Kai Burghardtbypass redirects [cf. discussion]
Kai Burghardtbypass [previously missed] redirect [cf. discussion]
Kai Burghardtbypass language bar/categorization template redirect [cf. discussion] (minor)

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.