Emulating+the+C+assignment+function

//by Richard Russell, July 2009//

In the **C** programming language, an //assignment// operation such as:

code format="C" variable = expression code can be used either as a //statement// or as a //function//. When used as a function, it returns the new value of the variable. Whilst at first sight this might not seem very useful, it is particularly convenient in the case of a **while** loop, for example:

code format="C" while (variable = expression) {         // Do something useful here } code Here **variable** is set equal to the value of **expression** and if its new value is //non-zero// the body of the loop is executed (note that it is //not// testing whether **variable** is equal to **expression**; in **C** you do that using the == operator).

Since in BBC BASIC an assignment is a //statement//, you can't straightforwardly do this, and you have to code it as follows:

code format="bb4w" variable = expression WHILE variable REM Do something useful here variable = expression ENDWHILE code As you can see, this involves writing the assignment statement **twice**, once outside the loop and again inside the loop. This is inelegant and potentially error-prone, for example you might make a change to one of the assignments but forget to change the other.

To emulate the **C** behaviour you can utilise this simple function:

code format="bb4w" DEF FNassign(RETURN variable, expression) variable = expression = variable code Now you can write the loop as follows:

code format="bb4w" WHILE FNassign(variable, expression) REM Do something useful here ENDWHILE code Note that since **variant** numeric variables are used in the function (i.e. without a 'type' suffix character) it will work equally well with **integer** variables and values as with **floating-point** variables.