Can IF and ELSE be nested?
Posted: Tue Jul 13, 2021 12:33 am
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.
If 'condition1' is set to 1 instead of 0, the program works as expected and ends without an error; serial monitor output below: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.
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
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
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