🎓 A1Learner
🔍
0 of 46 lessons completed

Zig C Structs

A C struct is a group of related values bundled under one name. The C library defines some structs, and Zig can read their fields.

Quotient and remainder

One division call returns both results in a single struct value. The fields are read by name.

const std = @import("std");
const c = @cImport({
    @cInclude("stdlib.h");
});
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const d = c.div(17, 5);
    try out.print("quot: {d} rem: {d}\n", .{ d.quot, d.rem });
}

Long division

The long form of the division call works on larger integers. Its struct carries the same two fields.

const std = @import("std");
const c = @cImport({
    @cInclude("stdlib.h");
});
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const ld = c.ldiv(100, 7);
    try out.print("lquot: {d} lrem: {d}\n", .{ ld.quot, ld.rem });
}

Building a struct value

A struct value can be written directly with its fields named. This program builds one and prints both fields.

const std = @import("std");
const c = @cImport({
    @cInclude("stdlib.h");
});
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const made: c.div_t = .{ .quot = 10, .rem = 3 };
    try out.print("made: {d} {d}\n", .{ made.quot, made.rem });
}

Example

const std = @import("std");
const c = @cImport({
    @cInclude("stdlib.h");
});
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const t = c.div(137, 60);
    try out.print("{d} hours {d} minutes\n", .{ t.quot, t.rem });
}

Key points

  • Field: a field is one named value inside a struct.
  • Quotient: a quotient is the whole number of times one number fits into another.
  • Remainder: a remainder is the amount left over after a division.
  • A division call returns one struct value that carries both results at once.
  • Long division: long division is a division that works on larger C integers.
  • A struct value can also be built by hand by naming each field in turn.

The program divides 137 minutes by 60 minutes per hour. The quotient is the hour count and the remainder is the leftover minutes. The single printed line reads like a time.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which field of a division result holds the leftover amount?