Zig Flow Control
Zig programming language flow control statements are determined by the program setting one or more conditional statements.
When the condition is true, the specified program code is executed; when the condition is false, other specified code is executed.
The following is a typical flow control flowchart:
Zig provides the following control structure statements:
if Statement
Syntax
A basic if statement contains a condition and an associated code block. If the condition is true, the code block is executed.
if (<condition) {
// 如果 condition 为 true,执行这里的代码
}
The if-else statement adds an else branch to the basic if statement. If the condition in the if is false, the code in the else branch is executed.
if (<condition>) {
// 如果 condition 为 true,执行这里的代码
} else {
// 如果 condition 为 false,执行这里的代码
}
condition:A boolean expression. If the condition is true, the first code block is executed; otherwise, the else code block is executed.
Example
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", .{});
}
}
The output after compilation and execution is:
x is greater than 5
if-else...else Statement
Syntax
Supports multiple condition checks, checking each condition in order until a condition is true and the corresponding code block is executed.
Example
// If condition1 is true, execute the code here
} else if (condition2) {
// If condition2 is true, execute the code here
} else {
// If all conditions are false, execute the code here
}
Example
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", .{});
}
}
The output after compilation and execution is:
x is equal to 10
Nested if-else
if-else statements can be nested, meaning you can include another if statement within an if or else branch.
if (<条件1>) {
// 如果条件1为真,执行这里的代码
if (<条件2>) {
// 如果条件1和条件2都为真,执行这里的代码
} else {
// 如果条件1为真但条件2为假,执行这里的代码
}
} else {
// 如果条件1为假,执行这里的代码
}
Example
pub fn main() void {
const input = 5; // Assume this is the user's input
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});
}
}
}
The output after compilation and execution is:
Input is between 5 and 10
Type Inference in if Statements
The Zig compiler can infer the type of variables in if statements, if the result of the conditional expression is a boolean value.
const condition = true;
if (condition) {
// 这里 condition 的类型是 bool,编译器自动推导
}
Other Extensions