BBC BASIC equivalent of the 'spaceship' operator

Discussions about the BBC BASIC language, with particular reference to BB4W and BBCSDL
Richard Russell
Posts: 272
Joined: Tue 18 Jun 2024, 09:32

BBC BASIC equivalent of the 'spaceship' operator

Post by Richard Russell »

When translating code from another language to BBC BASIC you may occasionally encounter the so-called spaceship operator <=>; languages which have this three-way comparison operator include Perl, Ruby, PHP and C++.

There's a straightforward conversion to BBC BASIC: a <=> b is equivalent to SGN(a - b).

For example in PHP you might have:

Code: Select all

echo x <=> y;
In BBC BASIC this would be:

Code: Select all

PRINT SGN(x - y)
Richard Russell
Posts: 272
Joined: Tue 18 Jun 2024, 09:32

Re: BBC BASIC equivalent of the 'spaceship' operator

Post by Richard Russell »

Richard Russell wrote: Wed 06 Nov 2024, 22:41There's a straightforward conversion to BBC BASIC: a <=> b is equivalent to SGN(a - b).
The Wikipedia article correctly points out that if you are extremely unlucky you may have a pair of numbers a, b which can be legitimately compared but when subtracted may result in an overflow (and hence an error being reported). If this is a concern an alternative BBC BASIC formulation of a <=> b is (a < b) - (a > b).

In PHP:

Code: Select all

echo x <=> y;
In BBC BASIC (method 1):

Code: Select all

PRINT SGN(x - y)
In BBC BASIC (method 2):

Code: Select all

PRINT (x < y) - (x > y)
This alternative method can't be used if a and/or b are expressions containing function calls which may have side-effects, since they will be called twice.