Pascal - 內嵌 if-then 語句



Pascal 程式設計中巢狀 if-else 語句始終是合法的,這意味著你可以在另一個 ifelse if 語句中使用一個 ifelse 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 關鍵字匹配第一個 if 關鍵字(向後搜尋),尚未透過 else 關鍵字匹配。

上述語法等效於

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;

因此,如果情況需要後一種結構,則必須在正確的位置放置 beginend 關鍵字。

示例

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
pascal_decision_making.htm
廣告
© . All rights reserved.