Else

From Free Pascal wiki
Revision as of 22:44, 26 October 2010 by Rfc1394 (talk | contribs)
Jump to navigationJump to search

Else is keyword which introduces the action to do if the condition is false.

If then else

<delphi>

 if (condition)
 then (action)
 else (action);

</delphi>

More statements in "if then else" statement

If you need two or more statements in "if then else" statement. In that case, you need a begin ... end Block around the statements.

<delphi>

 if boolean_condition then
   begin
     statement_one;
     statement_two;
   end 
 else
   begin
     statement_three;
     statement_four;
   end;

</delphi>

In regular usage, the "else" statement is a special exception to the rule that every statement is followed by a semicolon. Neither the "else" keyword nor the statement immediately preceding it may have a semicolon following it. In the above example the first "end" statement is not followed by a semicolon but the last one is.

However, in the case of nested "if" statements, if the else applies to the "inner" if, then the semicolon must not appear before the else, if the else applies to the outer else, then a semicolon must appear before it:

<delphi>

 if a then
     if b then 
       begin
          (..)
       end;
     else
       begin
          (..)
       end;

</delphi> In this case, the "else" applies to "if a" <delphi>

 if a then
     if b then 
       begin
          (..)
       end
     else
       begin
          (..)
       end;

</delphi> In this case, the "else" applies to "if b". If this causes ambiguity, it can be resolved by coding <delphi>

 if a then
     if b then 
       begin
          (..)
       end
     else
 else
     begin
          (..)
     end

</delphi>


Keywords: begindoelseendforifrepeatthenuntilwhile