Lesson 4 of 28
Lesson Progress: 0%
Variables let you store and change data while your program runs. In Zig, you declare a mutable variable with the var keyword followed by its name, type, and initial value. Once declared, you can reassign the variable by using its name on the left side of an equals sign. Variables must be declared before they are used, and each variable has a specific type that determines what kind of data it can hold. Zig also supports type inference, letting you omit the type when it is obvious from the initial value. This lesson covers how to declare, initialize, and change variables.
const std = @import("std");
pub fn main() void {
const x: i32 = 10;
std.debug.print("{d}", .{x});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
var x: i32 = 10; declares a variable using the var keyword.i32 is the type, meaning a signed 32-bit integer.10 is assigned when the variable is created.var can be changed later in the program.const std = @import("std");
pub fn main() void {
var score: i32 = 100;
score = 95;
std.debug.print("{d}", .{score});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
score = 95; reassigns the variable to a new value.const std = @import("std");
pub fn main() void {
const count: u32 = 5;
const pi: f64 = 3.14;
const flag: bool = true;
std.debug.print("{d} {d} {any}", .{count, pi, flag});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
u32 is an unsigned 32-bit integer (only positive values).f64 is a 64-bit floating-point number for decimal values.bool stores a boolean value that is either true or false.const std = @import("std");
pub fn main() void {
const username = "Zig";
const year: u32 = 2024;
std.debug.print("{s} created in {d}", .{username, year});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
var username = "Zig"; infers the type as a string.var year = 2024; infers the type as an integer.const std = @import("std");
pub fn main() void {
var a: i32 = 10;
const b: i32 = 20;
a = a + b;
std.debug.print("{d}", .{a});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
a = a + b; reads the current value of a, adds b, and stores the result back.a and b must have compatible types for the operation.const std = @import("std");
pub fn main() void {
var value: i32 = 0;
value = value + 5;
value = value + 3;
std.debug.print("{d}", .{value});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
var gives you the flexibility to track changing state.Test Incomplete