Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.


4.1.1 IF block

The IF block has the following form (the bits like expression are descriptions of the kinds of E code which is allowed at that point--they are not proper E code):

  IF expressionA
    statementsA
  ELSEIF expressionB
    statementsB
  ELSE
    statementsC
  ENDIF

This block means:

There does not need to be an ELSE part but if one is present it must be the last part (immediately before the ENDIF). Also, there can be any number of ELSEIF parts between the IF and ELSE parts.

An alternative to this vertical form (where each part is on a separate line) is the horizontal form:

  IF expression THEN statementA ELSE statementB

This has the disadvantage of no ELSEIF parts and having to cram everything onto a single line. Notice the presence of the THEN keyword to separate the expression and statementA. This horizontal form is closely related to the IF expression, which is described below (see 4.1.2 IF expression).

To help make things clearer here are a number of E code fragments which illustrate the allowable IF blocks:

  IF x>0 THEN x:=x+1 ELSE x:=0

  IF x>0
    x:=x+1
  ELSE
    x:=0
  ENDIF

  IF x=0 THEN WriteF('x is zero\n')

  IF x=0
    WriteF('x is zero\n')
  ENDIF

  IF x<0
    Write('Negative x\n')
  ELSEIF x>2000
    Write('Too big x\n')
  ELSEIF (x=2000) OR (x=0)
    Write('Worrying x\n')
  ENDIF

  IF x>0
    IF x>2000
      WriteF('Big x\n')
    ELSE
      WriteF('OK x\n')
    ENDIF
  ELSE
    IF x<-800 THEN WriteF('Small x\n') ELSE Write('Negative OK x')
  ENDIF

In the last example there are nested IF blocks (i.e., an IF block within an IF block). There is no ambiguity in which ELSE or ELSEIF parts belong to which IF block because the beginning and end of the IF blocks are clearly marked. For instance, the first ELSE line can be interpreted only as being part of the innermost IF block.

As a matter of style the conditions on the IF and ELSEIF parts should not overlap (i.e., at most one of the conditions should be true). If they do, however, the first one will take precedence. Therefore, the following two fragments of E code do the same thing:

  IF x>0
    WriteF('x is bigger than zero\n')
  ELSEIF x>200
    WriteF('x is bigger than 200\n')
  ELSE
    WriteF('x is too small\n')
  ENDIF

  IF x>0
    WriteF('x is bigger than zero\n')
  ELSE
    WriteF('x is too small\n')
  ENDIF

The ELSEIF part of the first fragment checks whether x is greater than 200. But, if it is, the check in the IF part would have been true (x is certainly greater than zero if it's greater than 200), and so only the code in the IF part is executed. The whole IF block behaves as if the ELSEIF was not there.


Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.