User Tools

Site Tools


emulating_20the_20c_20assignment_20function

This is an old revision of the document!


Emulating the C assignment function

by Richard Russell, July 2009

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

      variable = expression

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:

      while (variable = expression)
        {
          // Do something useful here
        }

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:

      variable = expression
      WHILE variable
        REM Do something useful here
        variable = expression
      ENDWHILE

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:

      DEF FNassign(RETURN variable, expression)
      variable = expression
      = variable

Now you can write the loop as follows:

      WHILE FNassign(variable, expression)
        REM Do something useful here
      ENDWHILE

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.

This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information
emulating_20the_20c_20assignment_20function.1522502358.txt.gz · Last modified: 2018/03/31 13:19 by 127.0.0.1