Skip to content
Kavachकवच

If...Else

Also known as: if else elif else if conditional ternary branch condition

● Beginner4 minBefore this: Operators, BooleansSpec 4.1

if runs a block only when its condition is true; else gives the other way.

Syntax

if condition {
    // when condition is true
} else {
    // otherwise
}
syntax: Kavach code

Example

fn main() {
    const stock = 3
    if stock == 0 {
        print("Sold out")
    } else if stock < 5 {
        print("Only {stock} left")
    } else {
        print("In stock")
    }
}

The program ran and printed:

kavach run else-if.kav

Only 3 left
else-if.kav: Kavach code, then what running it prints

The conditions are tried top to bottom, and only the first true one runs its block.

The condition must be a Bool. if stock is an error; write what you mean, such as if stock > 0.

= is not ==

= sets a variable, and only as a statement of its own. In a condition it is an error that says what to write instead. The same holds for while:

fn main() {
    const stock = 4
    if stock = 4 {
        print("four left")
    }
}

The compiler refused the program:

kavach run equals.kav

error: `=` sets a variable: to compare, write `==` (spec 4.1)
equals.kav: Kavach code, then what running it prints

A branch that can never run

Conditions are tried in order, so a wider one first hides a narrower one after it. The compiler warns:

fn grade(score: Int) -> String {
    if score > 10 {
        "good"
    } else if score > 50 {
        "great"
    } else {
        "keep going"
    }
}

fn main() {
    print(grade(70))
}

The compiler warned, then the program ran:

kavach run never-true.kav

warning: this condition is never true here: `score > 50` means `score > 10`, and that branch is taken above. Check the order of the conditions (spec 4.7)good
never-true.kav: Kavach code, then what running it prints

In the editor, the quick fix "Remove this branch" takes out the else if and its block. An else after it stays, joined to the branch before.

One page for each form

Try it yourself

Given a number n, print whether it is even or odd.
Show the answer
fn main() {
    const n = 7
    if n % 2 == 0 {
        print("{n} is even")
    } else {
        print("{n} is odd")
    }
}

The program ran and printed:

kavach run even-odd.kav

7 is odd
even-odd.kav: Kavach code, then what running it prints

What Kavach does for you

  • No truthiness

    A condition must be a Bool. if count is an error, so 0, "" and none can never be taken for false by accident.

    spec 4.1

Check yourself

QUIZ 1 / 1type what it prints
What does this print?
const stock = 0
if stock == 0 {
    print("Sold out")
} else if stock < 5 {
    print("Few left")
} else {
    print("In stock")
}