Can IF and ELSE be nested?

Recurrent H/W and software problems
Post Reply
ebs
Posts: 14
Joined: Fri Jun 25, 2021 2:33 pm
Been thanked: 2 times

Can IF and ELSE be nested?

Post by ebs »

I see in the help file that IF statements can be nested, but is it possible to next IF/ELSE statements?

For example, in the program below, I would expect to see the message "else1", since 'condition1' equals 0.
Instead I see "else2", which tells me that the program jumped to the first ELSE statement, not the second one.
I confirmed this by stepping through the code. Also, the program ended with an error.
The full output from the serial monitor is below the program listing.

Code: [Local Link Removed for Guests]

condition1 = 0
condition2 = 0

if condition1
  print "if1"
  if condition2
    print "if2"
  else
    print "else2"
  endif
else
  print "else1"
endif

Code: [Local Link Removed for Guests]

Program Running
Program paused at line 2
Program paused at line 3
Program paused at line 4
Program paused at line 9
else2
Program paused at line 10
Program paused at line 11
Program paused at line 13
ENDIF without IF line 13
Program Ended
If 'condition1' is set to 1 instead of 0, the program works as expected and ends without an error; serial monitor output below:

Code: [Local Link Removed for Guests]

Program Running
Program paused at line 2
Program paused at line 3
Program paused at line 4
Program paused at line 5
if1
Program paused at line 6
Program paused at line 9
else2
Program paused at line 10
Program paused at line 11
Program paused at line 13
Program Ended
Is there a way to make this program work correctly regardless of the values of the variables?

EDIT: I just determined that using THEN after the two IF statements makes the program work correctly (listings below).
This sounds like a good reason NOT to consider the THEN statement optional.

Code: [Local Link Removed for Guests]

condition1 = 0
condition2 = 0

if condition1 then
  print "if1"
  if condition2 then
    print "if2"
  else
    print "else2"
  endif
else
  print "else1"
endif

Code: [Local Link Removed for Guests]

Program Running
Program paused at line 2
Program paused at line 3
Program paused at line 4
Program paused at line 12
else1
Program paused at line 13
Program Ended
User avatar
cicciocb
Site Admin
Posts: 1889
Joined: Mon Feb 03, 2020 1:15 pm
Location: Toulouse
Has thanked: 405 times
Been thanked: 1261 times
Contact:

Re: Can IF and ELSE be nested?

Post by cicciocb »

[Local Link Removed for Guests] wrote: [Local Link Removed for Guests]Tue Jul 13, 2021 12:33 am EDIT: I just determined that using THEN after the two IF statements makes the program work correctly (listings below).
This sounds like a good reason NOT to consider the THEN statement optional.
Yes, the THEN should always be used.
it can be considered optional only on single line IF like

Code: [Local Link Removed for Guests]

if a = b print "equal" else print "different"
Post Reply