Blocks – keeping your variables on a tight leash
In Zig, blocks are used to limit the scope of variable declarations.
Think of them as little cages that keep your variables from running wild across your entire program.
Here's a simple example:
pub fn main() void {
{
var x: i32 = 1;
x += 1;
}
// Trying to access x here will result in an error
// x += 1; // Error: x is undefined here
}
Inside the inner { ... } block, we declare a variable, x. Once we exit that block, x ceases to exist. Trying to use x outside its scope is like trying to use a library card after it's been revoked—not gonna happen.
Blocks in Zig aren't just for scoping; they can also act as expressions, meaning they can produce a value, as we can see in the following snippet:
const std = @import("std");
pub fn main() void {
const result = blk: {
const a = 10;...