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


4.1.2 IF expression

IF is such a commonly used construction that there is also an IF expression. The IF block is a statement and it controls which lines of code are executed, whereas the IF expression is an expression and it controls its own value. For example, the following IF block:

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

can be written more succinctly using an IF expression:

  y:=(IF x>0 THEN x+1 ELSE 0)

The parentheses are unnecessary but they help to make the example more readable. Since the IF block is just choosing between two assignments to y it isn't really the lines of code that are different (they are both assignments), rather it is the values that are assigned to y that are different. The IF expression makes this similarity very clear. It chooses the value to be assigned in just the same way that the IF block choose the assignment.

The IF expression has the following form:

  IF exp THEN expA ELSE expB

As you can see, IF expressions are written like the horizontal form of the IF block. However, there must be an ELSE part and there can be no ELSEIF parts. This means that the expression will always have a value (either expA or expB, depending on the value of exp), and it isn't cluttered with lots of cases.

Don't worry too much about IF expressions, since there are only useful in a handful of cases and can always be rewritten as a more wordy IF block. Having said that they are very elegant and a lot more readable than the equivalent IF block.


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