Else

From Lazarus wiki
Revision as of 13:40, 2 April 2018 by Bart (talk | contribs) (→‎If then else: avoid ambiguity by using compound statements in all if..then..else branches)
Jump to navigationJump to search

Deutsch (de) English (en) español (es) suomi (fi) français (fr) русский (ru)

Else at Language Reference

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

If then else

  if (condition)
  then true_statement
  else false_statement;

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.

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

Notice that before the else keyword, no semicolon (;) is allowed. In the above example the first "end" statement is not followed by a semicolon but the last one is.

The following code wil not compile:

    if a then
      if b then
        begin
           (..)
        end;
      else   // Fatal: Syntax error, ";" expected but "ELSE" found
        begin
           (..)
        end;

Having nested if..then..else statement can easlily lead to ambiguity: which else belongs to which if? In this case, the "else" applies to "not if b"

  if a then
      if b then
        begin
           DoB;
        end
      else
        begin
           DoNotB;
        end;

In this case, the "else" applies to "not if a". If this causes ambiguity, it can be resolved by coding an "empty" else statement:

  if a then
      if b then
        begin
          DoB
        end
      else
  else
      begin
        DoNotA
      end;

You can avoid this kind af ambiguity by using begin..end blocks for all branches in nested if..then..else statements.

  if a then
    begin // a=true
      if b then
        begin //a=true, b=true
          DoAandB;
        end
    end
    else // if a
      begin
        if b then
          begin //a=false, b=true
            DoSomethingCompletelyDifferent;
          end
        else //if b
          begin // a=false, b=false
            DoNotA_NotB;
          end;
      end;



Keywords: begindoelseendforifrepeatthenuntilwhile