目录

嵌套if语句(nested if statements)

在Pascal编程中嵌套if-else语句总是合法的,这意味着你可以在另一个ifelse if语句中使用ifelse if语句。 Pascal允许嵌套到任何级别,但是,如果依赖于特定系统上的Pascal实现。

语法 (Syntax)

嵌套if语句的语法如下 -

if( boolean_expression 1) then
   if(boolean_expression 2)then S1
else
   S2;

您可以使用与嵌套if-then语句类似的方式嵌套if-then-else。 请注意,嵌套的if-then-else结构会引起一些歧义,即if语句与哪些else语句对。 The rule is that the else keyword matches the first if keyword (searching backwards) not already matched by an else keyword.

上面的语法相当于

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关键字放在正确的位置。

例子 (Example)

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
↑回到顶部↑
WIKI教程 @2018