# Comments and Documentation

### Comments and Documentation

Comments are notes for humans who read the code.

The compiler mostly ignores comments. They do not change what the program does. Their job is to explain intent, warn about important details, or make code easier to understand.

#### Line Comments

A normal comment starts with `//`.

```zig
// This is a comment.
const x = 10;
```

Everything after `//` on the same line is a comment.

```zig
const x = 10; // x starts at 10
```

Use line comments when you need to explain one small idea.

#### Comments Should Explain Why

A weak comment repeats the code:

```zig
// Add 1 to count.
count += 1;
```

The code already says that.

A better comment explains why the increment matters:

```zig
// Count this record because it passed validation.
count += 1;
```

Good comments usually explain context, reason, or danger.

#### Avoid Obvious Comments

This is too noisy:

```zig
// Create an integer named age.
const age: u8 = 30;

// Print the age.
std.debug.print("{}\n", .{age});
```

The code is already clear.

Prefer comments only when they add useful information.

```zig
// The protocol stores age in one byte.
const age: u8 = 30;
```

Now the comment explains why the type is `u8`.

#### Block Comments

Zig does not use C-style block comments like this:

```c
/*
   comment
*/
```

Use repeated line comments instead:

```zig
// This is a longer explanation.
// It uses several line comments.
// Each line starts with //.
```

This keeps comments simple and easy to scan.

#### Documentation Comments

Zig has special comments for documentation.

A declaration documentation comment starts with `///`.

```zig
/// Returns the square of x.
fn square(x: i32) i32 {
    return x * x;
}
```

This comment belongs to the declaration immediately after it.

You can use this for functions, structs, constants, and other declarations.

```zig
/// A point in 2D space.
const Point = struct {
    x: i32,
    y: i32,
};
```

Documentation comments are meant for public explanations. They should describe what a declaration means and how to use it.

#### Container Documentation Comments

A container documentation comment starts with `//!`.

It documents the current file, struct, enum, union, or other container.

At the top of a file:

```zig
//! Small examples for learning Zig variables and types.

const std = @import("std");
```

Inside a struct:

```zig
const Config = struct {
    //! Runtime configuration for the server.

    port: u16,
    debug: bool,
};
```

Use `//!` when the comment describes the surrounding container. Use `///` when the comment describes the declaration below it.

#### `///` vs `//!`

The difference is important.

```zig
/// Describes the next declaration.
fn add(a: i32, b: i32) i32 {
    return a + b;
}
```

Here, `///` documents `add`.

```zig
//! Describes the current file or container.

const std = @import("std");
```

Here, `//!` documents the file.

A simple rule:

```text
/// explains what comes next
//! explains where you are now
```

#### Documenting Functions

A useful function comment should say what the function does, what the inputs mean, and any important behavior.

```zig
/// Returns true if age is at least 18.
fn isAdult(age: u8) bool {
    return age >= 18;
}
```

For a more detailed function:

```zig
/// Copies src into dest.
///
/// Returns the number of bytes copied.
/// If dest is smaller than src, only dest.len bytes are copied.
fn copyPrefix(dest: []u8, src: []const u8) usize {
    const n = @min(dest.len, src.len);
    @memcpy(dest[0..n], src[0..n]);
    return n;
}
```

This comment explains behavior that may not be obvious from the name alone.

#### Documenting Structs

For structs, explain what the value represents.

```zig
/// A rectangular area measured in pixels.
const Rect = struct {
    x: i32,
    y: i32,
    width: u32,
    height: u32,
};
```

If the fields need explanation, comment them too.

```zig
/// TCP server configuration.
const ServerConfig = struct {
    /// Port number from 0 to 65535.
    port: u16,

    /// Maximum number of simultaneous clients.
    max_clients: usize,

    /// Whether extra debug logs are enabled.
    debug: bool,
};
```

Do not document every field when the names are already obvious. Add documentation where it prevents confusion.

#### Comments and Public APIs

Public APIs need better comments than private helper code.

This is especially true for libraries.

```zig
/// Parses a decimal unsigned integer from text.
///
/// Returns error.InvalidCharacter if text contains a non-digit byte.
/// Returns error.Overflow if the result cannot fit in u64.
pub fn parseU64(text: []const u8) !u64 {
    var result: u64 = 0;

    for (text) |byte| {
        if (byte < '0' or byte > '9') {
            return error.InvalidCharacter;
        }

        const digit: u64 = byte - '0';
        result = result * 10 + digit;
    }

    return result;
}
```

The caller can now understand what errors may happen.

#### Comments Should Stay Accurate

Wrong comments are worse than no comments.

```zig
// Allow only adults.
if (age >= 16) {
    return true;
}
```

The comment says adults, but the code allows age 16. The reader now has two conflicting sources of truth.

When code changes, update the comment.

Better:

```zig
// This service allows users who are at least 16.
if (age >= 16) {
    return true;
}
```

Or remove the comment if the code is already clear.

#### Commenting Temporary Work

Sometimes you need to mark unfinished code.

```zig
// TODO: Handle IPv6 addresses.
```

Common tags:

| Tag | Meaning |
|---|---|
| `TODO` | something should be done later |
| `FIXME` | known broken behavior |
| `NOTE` | important context |
| `HACK` | intentional workaround |
| `SAFETY` | explanation for unsafe or delicate code |

Example:

```zig
// SAFETY: buffer[0..text.len] is valid because text.len <= buffer.len.
@memcpy(buffer[0..text.len], text);
```

A `SAFETY` comment is useful when code relies on a condition that the compiler may not fully express.

#### Do Not Use Comments to Hide Bad Names

This is weak:

```zig
// Number of users.
const n = 42;
```

Better:

```zig
const user_count = 42;
```

Good names reduce the need for comments.

Use comments for facts that names cannot easily express.

```zig
// The file format stores this field as little-endian u32.
const user_count = readU32Little(bytes);
```

#### A Complete Example

```zig
const std = @import("std");

/// User account state.
const User = struct {
    /// Unique numeric identifier.
    id: u64,

    /// Display name encoded as UTF-8.
    name: []const u8,

    /// Whether the account can log in.
    active: bool,
};

/// Returns true if the user is allowed to log in.
fn canLogin(user: User) bool {
    return user.active;
}

pub fn main() void {
    const user = User{
        .id = 1,
        .name = "Ada",
        .active = true,
    };

    if (canLogin(user)) {
        std.debug.print("{s} can log in\n", .{user.name});
    }
}
```

Output:

```text
Ada can log in
```

The comments explain the data model and function behavior. They do not repeat every line of code.

#### The Main Idea

Comments are for readers.

Use `//` for ordinary notes. Use `///` to document the declaration that follows. Use `//!` to document the current file or container.

Good comments explain why code exists, what assumptions it depends on, and how public APIs should be used. Avoid comments that merely repeat obvious code.

