Difference between revisions of "Else"

From Lazarus wiki
Jump to navigationJump to search
Line 4: Line 4:
 
<delphi>
 
<delphi>
 
   if (condition)
 
   if (condition)
   then (action)
+
   then ''true_statement''
   else (action);
+
   else ''false_statement'';
 
</delphi>
 
</delphi>
 +
 +
The value of ''condition'' is evaluated, if it resolves to true, the ''true_statement'' is executed, otherwise the ''false_statement'' is executed.  The value of condition ''must'' resolve to a boolean value or an error occurs.
  
 
=== More statements in "if then else" statement ===
 
=== 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|begin]] ... [[End|end]] [[Block]] around the statements.
+
If you need two or more statements for true_statement or false_statement, then the group of statements must be placed within a [[Begin|begin]] ... [[End|end]] [[Block]].
  
 
<delphi>
 
<delphi>

Revision as of 22:53, 26 October 2010

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

If then else

<delphi>

 if (condition)
 then true_statement
 else false_statement;

</delphi>

The value of condition is evaluated, if it resolves to true, the true_statement is executed, otherwise the false_statement is executed. The value of condition must resolve to a boolean value or an error occurs.

More statements in "if then else" statement

If you need two or more statements for true_statement or false_statement, then the group of statements must be placed within a begin ... end Block.

<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 an "empty" else statement: <delphi>

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

</delphi>


Keywords: begindoelseendforifrepeatthenuntilwhile