Section 3.2

if and else

Running one thing or another — and why a condition has to be a bool.

A comparison gives back true or false. if uses that to choose what the program runs.

@entry(start)
object MyProgram {
    start() {
        var temperature := 0;

        if (temperature > 0) {
            Console.print(text: "above zero");
        } else if (temperature < 0) {
            Console.print(text: "below zero");
        } else {
            Console.print(text: "exactly zero");
        }
    }
}

temperature is zero: neither above nor below. Change its value and the output changes.

Three branches, one taken

if tests its condition. If it is true, it runs the block that follows and skips all the rest; otherwise it moves on to the else if, then to the else if none answered. One branch runs, always — even where two conditions could have been true, the first one wins.

The final else is not compulsory. Without it, a program whose conditions are all false simply does none of that block and carries on below.

The parentheses are not optional

if (temperature > 0) — the parentheses around the condition are compulsory, and that is the rule everywhere a condition appears in the language. No exceptions, so nothing to memorise case by case.

A condition is a bool, never a number

This is what sets Archon apart from many languages, and it takes one line to show:

var n := 1;
if (n) { … }
error[T002]: the condition of a 'if' must be a 'bool', not a 'int64'
             (no implicit conversion from 0/1)

Elsewhere, 0 counts as “false” and everything else as “true”. Not here: an integer is a number, not an answer to a question. If you meant to ask “is n non-zero?”, write it — if (n != 0). The condition then says what it tests, instead of leaving it to be guessed.

That refusal has a cost, a couple of characters to type, and a gain: a condition can no longer mean anything other than what it looks like it means.

Your turn

  • Give temperature a positive value, then a negative one, and check that each branch is reached.
  • Remove the final else and give temperature the value zero: the program prints nothing, and that is correct.
  • Write if (temperature) with no comparison, and read the refusal in full — it names the type it expected and the one it found.