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


10.3 Assignments

We've already seen some assignments--these were assignment statements. Assignment expressions are similar except (as you've guessed) they can be used in expressions. This is because they return the value on the right-hand side of the assignment as well as performing the assignment. This is useful for efficiently checking that the value that's been assigned is sensible. For instance, the following code fragments are equivalent, but the first uses an assignment expression instead of a normal assignment statement.

  IF (x:=y*z)=0
    WriteF('Error: y*z is zero (and x is zero)\n')
  ELSE
    WriteF('OK: y*z is not zero (and x is y*z)\n')
  ENDIF

  x:=y*z
  IF x=0
    WriteF('Error: y*z is zero (and x is zero)\n')
  ELSE
    WriteF('OK: y*z is not zero (and x is y*z)\n')
  ENDIF

You can easily tell the assignment expression: it's in parentheses and not on a line by itself. Notice the use of parentheses to group the assignment expression. Technically, the assignment operator has a very low precedence. Less technically, it will take as much as it can of the right-hand side to form the value to be assigned, so you need to use parentheses to stop x getting the value `((y*z)=0)' (which will be TRUE or FALSE, i.e., -1 or zero).

Assignment expressions, however, don't allow as rich a left-hand side as assignment statements. The only thing allowed on the left-hand side of an assignment expression is a variable name, whereas the statement form allows:

  var
  var [ expression ]
  var . obj_element_name
  ^ var 

(With as many repetitions of object element selection and/or array indexing as the elements' types allow.) Each of these may end with ++ or -. Therefore, the following are all valid assignments (the last three use assignment expressions):

  x:=2
  x--:=1
  x[a*b]:=rubble
  x.apple++:=3
  x[22].apple:=y*z
  x[].banana.basket[6]:=3+full(9)
  x[].pear--:=fred(2,4)

  x.pear:=(y:=2)
  x[y*z].table[1].orange:=(IF (y:=z)=2 THEN 77 ELSE 33)
  WriteF('x is now \d\n', x:=1+(y:=(z:=fred(3,5)/2)*8))

You may be wondering what the ++ or - affect. Well, it's very simple: they only affect the var, which is x in all of the assignment statements above. Notice that x[].pear- is the same as x.pear-, for the same reasons mentioned earlier (see 9.4.2 Element selection and element types).


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