Zig フロー制御

Zigプログラミング言語のフロー制御文は、プログラムが1つ以上の条件文を設定することによって設定されます。

条件がtrueの場合は指定されたプログラムコードを実行し、条件がfalseの場合は他の指定されたコードを実行します。

以下は典型的なフロー制御のフローチャートです。

Zigは以下の制御構造文を提供します:

if 语句

语法

基本的なif文は、条件とそれに関連するコードブロックを含み、条件が真(true)の場合にコードブロックを実行します。

if (<condition) {
    // 如果 condition 为 true,执行这里的代码
}

if-else文は、基本のif文にelse分岐を追加したものであり、ifの条件が偽(false)の場合、else分岐内のコードを実行します。

if (<condition>) {
    // 如果 condition 为 true,执行这里的代码
} else {
    // 如果 condition 为 false,执行这里的代码
}

condition:ブール式です。条件がtrueの場合は最初のコードブロックを実行し、それ以外の場合はelseコードブロックを実行します。

实例

const std = @import("std");

pub fn main() void {
    const x: i32 = 10;
    if (x > 5) {
        std.debug.print("x is greater than 5\n", .{});
    } else {
        std.debug.print("x is not greater than 5\n", .{});
    }
}

コンパイル実行の出力結果は:

x is greater than 5

if-else...else 语句

语法

複数の条件チェックをサポートし、各条件を順番にチェックして、ある条件がtrueになった時点で対応するコードブロックを実行します。

实例

if (condition1) {
    // condition1 が true の場合、ここにあるコードを実行します
} else if (condition2) {
    // condition2 が true の場合、ここにあるコードを実行します
} else {
    // すべての条件が false の場合は、このコードを実行します
}

实例

const std = @import("std");

pub fn main() void {
    const x: i32 = 10;
    if (x > 10) {
        std.debug.print("x is greater than 10\n", .{});
    } else if (x == 10) {
        std.debug.print("x is equal to 10\n", .{});
    } else {
        std.debug.print("x is less than 10\n", .{});
    }
}

コンパイル実行の出力結果は:

x is equal to 10

ネストされた if-else

if-else文は入れ子にして使用できます。つまり、ifまたはelse分岐の中にさらにif文を含めることができます。

if (<条件1>) {
    // 如果条件1为真,执行这里的代码
    if (<条件2>) {
        // 如果条件1和条件2都为真,执行这里的代码
    } else {
        // 如果条件1为真但条件2为假,执行这里的代码
    }
} else {
    // 如果条件1为假,执行这里的代码
}

实例

const std = @import("std");

pub fn main() void {
    const input = 5; // これはユーザーの入力と仮定する
    const max_value = 10;

    if (input > max_value) {
        std.debug.print("Input is greater than {}\n", .{max_value});
    } else if (input == max_value) {
        std.debug.print("Input is equal to {}\n", .{max_value});
    } else {
        if (input < 5) {
            std.debug.print("Input is less than 5\n");
        } else {
            std.debug.print("Input is between 5 and {}\n", .{max_value});
        }
    }
}

コンパイル実行の出力結果は:

Input is between 5 and 10

if文における型推論

Zigコンパイラは、条件式の結果がブール値である場合、if文内の変数の型を推論できます。

const condition = true;
if (condition) {
    // 这里 condition 的类型是 bool,编译器自动推导
}
其他扩展