Pascal-nested-if-statement

提供:Dev Guides
移動先:案内検索

パスカル-ネストされたif-thenステートメント

Pascalプログラミングでは、 if-else ステートメントをネストすることは常に有効です。つまり、1つの if または else if ステートメントを別の if または else if ステートメント内で使用できます。 ただし、特定のシステムでPascalの実装に依存している場合、Pascalでは任意のレベルにネストできます。

構文

ネストされたif文の構文は次のとおりです-

if( boolean_expression 1) then
   if(boolean_expression 2)then S1

else
   S2;

if-thenステートメントをネストしたのと同様の方法で、else if-then-elseをネストできます。 ネストされた if-then-else 構造は、どのelseステートメントがどのifステートメントとペアになるかについて、あいまいさが生じることに注意してください。 elseキーワードは、elseキーワードとまだ一致していない最初のifキーワード(後方検索)に一致するという規則です。

上記の構文は次と同等です

if( boolean_expression 1) then
begin
   if(boolean_expression 2)then
      S1

   else
      S2;
end;

同等ではありません

if ( boolean_expression 1) then
begin
   if exp2 then
      S1
end;
   else
      S2;

したがって、状況によって後の構成が必要な場合は、 begin および end キーワードを適切な場所に配置する必要があります。

program nested_ifelseChecking;
var
   { local variable definition }
   a, b : integer;

begin
   a := 100;
   b:= 200;

   ( *check the boolean condition* )
   if (a = 100) then
      ( *if condition is true then check the following* )
      if ( b = 200 ) then
         ( *if nested if condition is true  then print the following* )
         writeln('Value of a is 100 and value of b is 200' );

   writeln('Exact value of a is: ', a );
   writeln('Exact value of b is: ', b );
end.

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200