If Else in Chapel

Branching with if and else in Chapel is straightforward.

use IO;

proc main() {
    // Here's a basic example.
    if 7 % 2 == 0 {
        writeln("7 is even");
    } else {
        writeln("7 is odd");
    }

    // You can have an `if` statement without an else.
    if 8 % 4 == 0 {
        writeln("8 is divisible by 4");
    }

    // Logical operators like `&&` and `||` are often
    // useful in conditions.
    if 8 % 2 == 0 || 7 % 2 == 0 {
        writeln("either 8 or 7 are even");
    }

    // A statement can precede conditionals; any variables
    // declared in this statement are available in the current
    // and all subsequent branches.
    var num = 9;
    if num < 0 {
        writeln(num, " is negative");
    } else if num < 10 {
        writeln(num, " has 1 digit");
    } else {
        writeln(num, " has multiple digits");
    }
}

Note that you don’t need parentheses around conditions in Chapel, but the braces are required.

To run the program:

$ chpl if-else.chpl -o if-else
$ ./if-else
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Chapel doesn’t have a ternary operator, so you’ll need to use a full if statement even for basic conditions.