Zig by Example: If/Else

If statements accept bool values (i.e. true or false).

const std = @import("std");
const print = std.debug.print;
pub fn main() !void {

Here we assign a as true to be validated further and use x.

    const a: bool = true;
    var x: u16 = 0;

Unlike languages like C or Javascript, there are no values that implicitly coerce to bool values, but the parentheses (…) are always required.

    if (a) {
        x += 1;
    } else {
        x += 2;
    }

Here we use a boolean expression to evaluate x.

    print("x = 1? {}\n", .{x == 1});

If statements also work as expressions.

    x += if (x == 1) 1 else 2;
    print("x now is: {d}\n", .{x});
}
$ zig run if-else.zig
x = 1? true
x now is: 2

Next example: Switch.