Search code examples
programming-languagesprogram-flow

Programming language without ELSE keyword - is it more complicated?


I'm working on a simple programming language for kids, based on Karel. For controlling program flow, I currently provide these facilities (in pseudocode):

  • defining parameterless procedures
  • if [not] EXPRESSION STATEMENT
  • while [not] EXPRESSION STATEMENT

I don't have any means to return from a procedure, and I don't provide the else statement.

Take the following code for an example:

if something
 statement1
if not something
 statement2

The execution of code flows to if, executing statement1 if something is true; then testing if something is not true (but the state of the program has changed!), then executing statement2. This can lead to both tests succeeding.

Does this limit the programmer? So far I've been able to solve all of my example problems by just using if ... if not ..., or using if not first, then if.

So, my question is: Is adding the else statement necessary? It would make the language a bit more complicated with having more keywords. Are all problems that would be solvable with else statement solvable also without it, albeit more complicated?

Or is omitting the else statement actually making the language more complicated and counter-intuitive?


Solution

  • If something is expensive to evaluate then your language with else might give a problem because the evaluation will be performed twice.

    Another potential problem is that if statement1 can modify the value of something you may end up with both tests succeeding - something that could not happen if you used else.

    Of course these problems can be mitigated by storing the result in a temporary local variable:

    bool result = something
    if result
        statement1
    if not result
        statement2
    

    So no you aren't limiting the programmer in what is possible - everything that can be done with else can be done without it by using the above approach. But it is a little more code to write each time and it introduces a few new potential problems for the unwary programmer that would be avoided if you allowed else.