BBC BASIC for Windows
Programming >> BBC BASIC language >> If Then Else
http://bb4w.conforums.com/index.cgi?board=language&action=display&num=1374687972

If Then Else
Post by Matt on Jul 24th, 2013, 5:46pm

Hi,

I have no good reason for asking this except for clearing up confusion. I'm a little fuzzy with the logic of this.

If:

Code:
(1)
IF A THEN IF B THEN PRINT 1 ELSE PRINT 2 

is the same as:

Code:
(2)
IF A THEN
  IF B THEN
    PRINT 1
  ELSE
    PRINT 2
  ENDIF
ENDIF 

or perhaps:

Code:
(3)
IF A THEN
  IF B THEN
    PRINT 1
  ENDIF
ELSE
  PRINT 2
ENDIF 


Why isn't:

Code:
(4)
IF A THEN IF B THEN PRINT 1 ELSE PRINT 2 ELSE PRINT 3 

the same as:

Code:
(5)
IF A THEN
  IF B THEN
    PRINT 1
  ELSE
    PRINT 2
  ENDIF
ELSE
  PRINT 3
ENDIF 

??

It's the route through the logic that is confusing me. I think I understand how each works, with the exception of (4). This seems to follow the same comparable logic as the others but doesn't give the same result - i.e. the action after the last ELSE is ignored. My logic (dubious, at best) suggests that the last ELSE is applied only if A is NOT TRUE. Yet it is the fist ELSE that is actioned when either A is NOT TRUE or B is NOT TRUE.

Matt
Re: If Then Else
Post by admin on Jul 24th, 2013, 9:29pm

on Jul 24th, 2013, 5:46pm, Matt wrote:
Code:
(4)
IF A THEN IF B THEN PRINT 1 ELSE PRINT 2 ELSE PRINT 3 


It's the route through the logic that is confusing me. I think I understand how each works, with the exception of (4).

When BBC BASIC evaluates a conditional expression as 'false' (i.e. zero) it searches along the line to see if there is an ELSE clause. If it finds an ELSE, it continues execution at that point, otherwise it continues execution on the next line.

As a result of this simple strategy, a second or subsequent ELSE will never be seen, so for example these three statements will always have an identical effect:

Code:
IF A THEN IF B THEN PRINT 1 ELSE PRINT 2
IF A THEN IF B THEN PRINT 1 ELSE PRINT 2 ELSE PRINT 3
IF A THEN IF B THEN PRINT 1 ELSE PRINT 2 ELSE PRINT 3 ELSE PRINT 4 

Richard.
Re: If Then Else
Post by Matt on Jul 25th, 2013, 05:38am

Simple as that.

Thanks Richard.

Matt