Zig Comments

Comments are not processed by the compiler; they are only used to add descriptions and explanations to code, helping developers understand the code logic.

In Zig, there are two forms of comments: single-line comments and multi-line comments.

1. Single-line Comments

Single-line comments start with//at the beginning; the comment content starts from//and ends at the end of the line.

Example

const std = @import("std");

// This is a single-line comment
pub fn main() void {
    std.debug.print("Hello, World!\n", .{});
}

2. Multi-line Comments

Multi-line comments start with/*at the beginning and end with*/at the end; the comment content can span multiple lines.

Example

const std = @import("std");

/*
This is a multi-line comment
It can span multiple lines
*/

pub fn main() void {
    std.debug.print("Hello, World!\n", .{});
}

Comment Usage

The following is a complete example containing single-line comments and multi-line comments, demonstrating how to add comments in code.

Example

const std = @import("std");

// Main function
pub fn main() void {
    // Call the standard library's debug.print function to print "Hello, World!"
    std.debug.print("Hello, World!\n", .{});
   
    /*
This code is used to demonstrate Zig's basic syntax
Including function definitions, standard library usage, and comments
    */

   
    const a: i32 = 10; // Define an integer constant a with a value of 10
    const b: i32 = 20; // Define another integer constant b with a value of 20

    // Call the add function and print the result
    const result = add(a, b);
    std.debug.print("Result: {}\n", .{result});
}

// A simple addition function
fn add(a: i32, b: i32) i32 {
    return a + b;
}
  • Single-line comments are used to explain individual lines or local code sections in the code.
  • Multi-line comments are used to describe larger sections of code.
Other Extensions