🎓 A1Learner
🔍
0 of 55 lessons completed

Zig Printing

Printing is how a Zig program shows values on the screen. A format specifier is a placeholder in the text that says how one value should appear.

Placeholders take values in order

The {s} placeholder takes the text value first. The {d} placeholder then takes the number.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{s} is {d} years old\n", .{ "Ana", 24 });
}

Hex and binary show other bases

The same value can print in different bases. Hex uses {x} and binary uses {b}.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("Hex: {x}\n", .{255});
    try out.print("Binary: {b}\n", .{5});
}

A byte can print as a character

The {c} specifier prints a byte as a character. The {d} specifier prints the same byte as its number code.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("Letter: {c}\n", .{'A'});
    try out.print("Code: {d}\n", .{'A'});
}

Example

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{s}: {d}\n", .{ "Score", 42 });
    try out.print("Hex: {x}\n", .{42});
    try out.print("Binary: {b}\n", .{42});
    try out.print("Letter: {c}\n", .{'Z'});
}

Key points

  • print: out.print sends a format string and its values to the screen.
  • Format string: a format string is the text in quotes, with placeholders where values belong.
  • Decimal: {d} prints a number in plain decimal form.
  • String: {s} prints a text value.
  • Hex: {x} prints a number in lowercase hexadecimal digits.
  • Binary: {b} prints a number in binary digits, using only 0 and 1.

In this example, the first print fills {s} with the text and {d} with the score. The next prints show the same score in hex and in binary, and the last print shows a byte as the letter Z.

Note

the values after the format string fill the placeholders in order.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the {x} specifier print?