else

Prev Next

Introduction

In contrast other names such as if(), while(), etc. which are control flow functions, else is one of the very few reserved keywords. else is used in combination with following functions:

  • if(): Used to run the statement or block if the condition inside if() is false.
  • once(): Used to run the statement or block if the condition inside once() is false, i.e. it is the 2nd or further time once() is encountered.
  • switch(): As default alternative to case() to cover all remaining case possibilities
  • check(): Same as above

If a code block with { ... } follows the else keyword, then you can formulate it like in a C/C++ or Java program. However if a single statement follows the else keyword, then you need to add a colon (:) to separate the 'else' from the following statement, otherwise it would cause some misinterpretations.


  define procedure ( else echo, {{ contents, all }} )
  {
      echo("Haha! Cought you!!  You tried to output ", contents[]);
  }

  define procedure( test 1, {{ value, numeral }} )
  {
      if (value[] = 5)
      {
          echo(five);
      }
      else: echo(not five); // This is the right formulation
  }

  define procedure( test 2, {{ value, numeral }} )
  {
      if (value[] = 5)
      {
          echo(five);
      }
      else echo(value[]); // Oops! Forgot the colon. Calling 'else echo' as procedure.
  }

  test 1 ( 5 );
  test 1 ( 6 );
  test 2 ( 5 ); // Watch the output
  test 2 ( 6 ); // Watch the output, too
five
not five
five
Haha! Cought you!!  You tried to output 5
Haha! Cought you!!  You tried to output 6
Try it yourself: Open LIB_Features_else.b4p in B4P_Examples.zip. Decompress before use.

See also

if
once
switch
check
case