<!-- PDF page 57 -->

You define a function by putting a **DEF** statement somewhere in the program. For instance, here is the definition of a function **FN s** whose result is the square of the argument:

```
DEF FN sq(x)=x*x: REM square of x
```

The **sq** following the **DEF FN** is the name of the function. The **x** in parentheses is a name by which you wish to refer to the argument of the function.

After the = sign comes the actual definition of the function. This can be any expression, and it can also refer to the argument using the name you've given it (in this case, **x**) as though it were an ordinary variable.

When you have entered this line, you can invoke the function just like one of the computer's own functions, by typing its name, **FN sq**, followed by the argument. Remember that when you have defined a function yourself, the argument must be enclosed in parentheses. Try it out a few times:

```
PRINT FN sq(2)

PRINT FN sq(3+4)

PRINT 1+INT FN sq (LEN "chicken"/2+3)
```

Once you have put the corresponding **DEF** statement into the program, you can use your own functions in expressions just as freely as you can use the computer's.

Note: in some dialects of BASIC you must even enclose the argument of one of the computer's functions in parentheses. This is not the case in *NextBASIC*.

**INT** always rounds down. To round to the nearest integer, add **.5** first – you could write your own function to do this:

```
20 DEF FN r(x)=INT (x+0.5):
   REM gives x rounded to the
   nearest integer.
```

You will then get, for instance:

<table>
<tbody>
<tr><td><strong>FN r(2.9) = 3</strong></td><td><strong>FN r(2.4) = 2</strong></td></tr>
<tr><td><strong>FN r(-2.9) = -3</strong></td><td><strong>FN r(-2.4) = -2</strong></td></tr>
</tbody>
</table>

Compare these with the answers you get when you use **INT** instead of **FN r**. Type in and run the following:

```
10 x,y,a=0,0,10
20 DEF FN p(x,y)=a+x*y
30 DEF FN q()=a+x*y
40 PRINT FN p(2,3),FN q()
```

There are a lot of subtle points in this program.

First, a function is not restricted to just one argument: it can have more, or even none at all – but you must still always keep the parentheses.

Second, it doesn't matter whereabouts in the program you put the **DEF FN** statements. After the computer has executed line 10, it simply skips over lines 20 and 30 to get to line 40. They do, however, have to be somewhere in the program. They can't be in a command.

Third, x and y are both the names of variables in the program as a whole, and the names of arguments for the function **FN p**. **FN p** temporarily forgets about the variables called **x** and **y**, but since it has no argument called **a**, it still remembers the variable **a**. In other words the exposed parameters of a function are always **LOCAL** within the function.

