Basic Pascal Tutorial/Chapter 3/IF/ja

From Lazarus wiki
Revision as of 10:19, 10 August 2015 by Derakun (talk | contribs)
Jump to navigationJump to search

български (bg) English (en) français (fr) 日本語 (ja) 中文(中国大陆)‎ (zh_CN)

3Ca - IF (著者: Tao Yue, 状態: 原文のまま修正なし)

IF 文はブール式の結果をもとに分岐を可能にする。 1方向の分岐の形式は次のようになる。

if ブール式 then
  真の場合の命令文;

もし、ブール式が true と評価されたなら、命令文が実行される。そうでない場合には、スキップされる。

IF 文は1つの命令文のみ受け取る。命令文の組み合わせで分岐させたいなら、 begin-end ブロック で命令文を囲む。

if ブール式 then
begin
  命令文1;
  命令文2
end;

2方向の分岐もある。

if ブール式 then
  真の場合の命令文
else
  偽の場合の命令文;

ブール式が FALSE と評価されると、 else に続く命令文が実行される。 else の前の命令文にはセミコロンをつけてはいけないことに注意しよう。つけてしまうと、コンピュータはそれを1方向の選択と扱い、 else がどこからきたのかわからないままになってしまうからである。

If you need multi-way selection, simply nest if statements:

if Condition1 then
  Statement1
else
  if Condition2 then
    Statement2
  else
    Statement3;

Be careful with nesting. Sometimes the computer won't do what you want it to do:

if Condition1 then
  if Condition2 then
    Statement2
else
  Statement1;

The else is always matched with the most recent if, so the computer interprets the preceding block of code as:

if Condition1 then
  if Condition2 then
    Statement2
  else
    Statement1;

You can get by with a null statement:

if Condition1 then
  if Condition2 then
    Statement2
  else
else
  Statement1;

Or you could use a begin-end block. But the best way to clean up the code would be to rewrite the condition.

if not Condition1 then
  Statement1
else
  if Condition2 then
    Statement2;

This example illustrates where the not operator comes in very handy. If Condition1 had been a Boolean like: (not(a < b) or (c + 3 > 6)) and g, reversing the expression would be more difficult than NOTting it.

Also notice how important indentation is to convey the logic of program code to a human, but the compiler ignores the indentation.


previous contents next