Classic Computer Magazine Archive COMPUTE! ISSUE 89 / OCTOBER 1987 / PAGE 10

Variable Operators?

When I type in and execute this line:

10 X = 2 * 6

the variable X contains a value of 12. But when I type in these lines:

10 OP$ = " * "
20 X = 2 OP$ 6

I get a syntax error. How can I make it so that I can change the operators in my expressions?

Scott K. Stephen

Line 10 of your second example, OP$ = "*", is perfectly legal. Any character can be assigned to a string variable. Line 20 is the problem. BASIC is familiar with operators called *, /, +, -, and others, but it doesn't know of one called OP$.

BASIC has a set of rules that determines whether an expression is allowed. Although a BASIC-like language could be devised to allow your statement in line 20, BASIC does not. The numbers 2 and 6 in your example are numeric operands. They can be replaced by variables. The asterisk (used for multiplication in BASIC and most other computer languages) is a numeric operator, and BASIC does not allow you to replace operators with variables.

One way to change the operators in expressions is to use the ON-GOSUB command. Here's an example:

10 INPUT B, C, OP
20 ON OP GOSUB 100, 200, 300, 400
30 PRINT A
40 END
100 A = B + C:RETURN
200 A = B - C:RETURN
300 A = B * C:RETURN
400 A = B / C:RETURN

When the program asks for input, respond like this:

4, 5, 1

The first operand is 4; 5 is the second operand; and 1 tells the program to use operator 1 (addition). Operator 2 is subtraction; operator 3 is multiplication; operator 4 is division.