if-else in bAdkOde

I was talking to my CSE 200 (my first CS class at ASU) professor Richard Whitehouse about bAdkOde and he (rightly) pointed out that it didn’t have an explicit selection statement. He also said that unless I wanted it to be really ugly I’d need to have a selection statement. However, since I was going for ugly I figured that I’d just emulate the operation of an if and an if-else with the existing while statement.

If you know assembly, then you know that a while is simply a set of statements wrapped with a conditional branch at the top and a backwards branch at the bottom (or in other words, an if with a goto at the end. A do-while is simply a set of statements with a conditional branch (at the bottom) that branches to the top of the loop. In fact, in assembly programming there really aren’t any for loops or while loops. These keywords are simply abstractions and syntactic sugar. In bAdkOde, you can implement an if with the existing while statement if you explicitly make it break out of the loop. For example, let’s say that we want to check whether the user entered the character “0”:

?a
-48a
# print a line break
"10
# if a is zero
{=a
 # print the string "zero"
 "122"101"114"111"10
 # set the a register to a non-zero value so that we can break out of the loop
 >1a
}

I knew there was a way to implement an if-else with just while statements but I didn’t remember exactly how. Then my friend and co-worker Juan reminded me that I needed two variables. In our case, we need to use two registers:

?a
-48a
# copy the value of a into b
>ab
"10
# if a is zero
{=a
 # print the string "zero"
 "122"101"114"111"10
 # set the a register to a non-zero value so that we can break out of the loop
 >1a
}
# if the top loop failed, it means that b (which holds the same value as a) is 
# non-zero and so we can enter this block.
# if the top loop was successful, it means that b (which holds the same value
# as a) is zero and so we won't enter this block. Hence, the second block acts
# as an 'else'
{!b
 # print the string "non-zero"
 "110"111"110"45"122"101"114"111"10
 # zero out the b register
 >0b
}

Yes, quite ugly. But that’s what I’m going for! 🙂