2.6. Conditionals

Next to loops, conditional expressions are also important language constructs. The ?: operator introduced in Section 2.2 is an example of a conditional expression: if the condition is TRUE, then execute what follows the ?, else execute what follows the :.

This section introduces a semantically equivalent to the ?: operator, but, as with a lot of TOM language constructs, with a syntax pleasing the eye accustomed to C.

The following example shows the use of the if else construct.


int
  main Array argv
{
  int n = [argv length];

  if (n == 0)
    [[[stdio out] print "no arguments"] nl];
  else
    [[[stdio out] print (n, " arguments")] nl];
}

If this program is invoked without any arguments, the Array argv will not contain any elements, and will return 0 when asked for its length. Consequently, the program's output will be no arguments. When invoked with at least one argument, it will report the number of elements in argv, which is the number of arguments.

When you have modified the hello program to have the above main method, the following is a example of its output when run.


$ ./hello
no arguments
$ ./hello tiny little program
3 arguments
$ ./hello "little robot"
1 arguments

And thus we discover a bug in our program: the output when invoked with a single argument is wrong since `1 arguments' is not proper English. You are hereby challenged to fix this, armed with the knowledge that what follows an else is an expression, just like the if else is an expression.

In contrast to the ?: operator, the else branch of an if else conditional is optional. If the condition evaluates to FALSE and the else branch is missing, the value of the whole expression becomes the default value of the expected type.

For example, after the following expressions, the value of a will be 0.


int b = 3;
int a = if (b < 0) b;