Zig Comments
A comment is a note inside code that the computer ignores. Comments explain the code to people who read it later.
A comment does not change the output
The comment line explains the program. Only the print line sends text to the screen.
const std = @import("std");
// This program greets the reader.
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("Hello!\n", .{});
}A comment can follow code on the same line
The code before the slashes still runs. The note after the slashes is ignored.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("Ready\n", .{}); // Tell the reader we are ready
}Commented-out code does not run
The first print line is a comment, so its text never appears. The second print line runs as normal.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
// try out.print("Hidden\n", .{});
try out.print("Visible\n", .{});
}Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
// Say that the game has started.
try out.print("Game started\n", .{});
// Say that the game has ended.
try out.print("Game over\n", .{});
}Key points
- Comment: a comment is text in the code that Zig ignores when it runs the program.
- //: two slashes start a comment, and the comment lasts to the end of that line.
- Placement: a comment can sit on its own line or after code on the same line.
- Use comments to explain why a line exists, not to repeat what the line plainly does.
- Commented out: code that is turned into a comment does not run.
In this example, each comment sits above the print line it explains. The comments send nothing to the screen, and the two print calls run in order.
Note
Zig has no block comments, so each comment line starts with its own //.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens to a comment when a Zig program runs?