[Q] are ORs and ANDs short-circuited?

Basic and Machine Language

Moderator: Moderators

Post Reply
pallas
Vic 20 Devotee
Posts: 212
Joined: Mon Dec 24, 2012 2:38 am

[Q] are ORs and ANDs short-circuited?

Post by pallas »

Hello,

I couldn't find this information by googling so I'm asking the gurus here.
Are the "and" and "or" operators short-circuited in basic v2?

http://en.wikipedia.org/wiki/Short-circuit_evaluation

I.e. (1 or a=1) will basic evaluate a=1?
User avatar
Mike
Herr VC
Posts: 4845
Joined: Wed Dec 01, 2004 1:57 pm
Location: Munich, Germany
Occupation: electrical engineer

Re: [Q] are ORs and ANDs short-circuited?

Post by Mike »

pallas wrote:Are the "and" and "or" operators short-circuited in basic v2?
No, they aren't. Expressions are always evaluated in full.

Furthermore, AND, OR and NOT operate on signed 16-bit quantities. The result of a relational operator ('=', '<', '>' or any combination thereof) is -1 if the relation is true, and is 0 when the relation is false. IF executes the THEN clause, if the numerical value between IF and THEN is non-zero.

Regarding the handling of statements and expressions in CBM BASIC, here's some more info.
pallas
Vic 20 Devotee
Posts: 212
Joined: Mon Dec 24, 2012 2:38 am

Post by pallas »

Thanks.
So an if statement with a complex condition might be optimized by splitting it into multiple if instructions?
User avatar
Mike
Herr VC
Posts: 4845
Joined: Wed Dec 01, 2004 1:57 pm
Location: Munich, Germany
Occupation: electrical engineer

Post by Mike »

Indeed, the form:

IF <condition_1> THEN IF <condition_2> THEN ...

instead of:

IF <condition_1> AND <condition_2> THEN ...

is quite often found in BASIC programs, and is easily generalised for more conditions.

Note however these are only equivalent, when all conditionals are Boolean expressions.

If you had, for example <condition_1> := 2 and <condition_2> := 4, then the THEN IF construct will execute the final THEN clause, but the AND construct wouldn't, as 2 AND 4 = 0.
pallas
Vic 20 Devotee
Posts: 212
Joined: Mon Dec 24, 2012 2:38 am

Post by pallas »

same can be done with OR, but since it would need a new line and repeating of the action for every added if statement, I suppose it's not used nor convenient.
User avatar
Kweepa
Vic 20 Scientist
Posts: 1315
Joined: Fri Jan 04, 2008 5:11 pm
Location: Austin, Texas
Occupation: Game maker

Post by Kweepa »

The best way to write a short-circuited OR is:

Code: Select all

REM BEFORE
IF A<0 OR R(A)>0.1 OR RND(1)<0.4 THEN PRINT "PHLEGM":GOTO 4

REM AFTER
X=0:IF A>=0 THEN IF R(A)<=0.1 THEN IF RND(1)>=0.4 THEN X=1
IF X=0 THEN PRINT "PHLEGM":GOTO 4
Post Reply