Skip to content

Zig for C Developers

If you know C, you already know most of what Zig is about: pointers, manual memory, structs, no garbage collector, compiling to a small native binary. Zig was designed by someone who wanted C’s directness without C’s sharp edges, and it shows. This page walks through the C habits you have and what Zig does instead, with each pair of programs side by side. Every C example here was compiled with gcc 13 and every Zig example with Zig 0.17.1.

In C In Zig Lesson
#include "file.h" const file = @import("file.zig"); Zig Modules
char * + strlen Slices: []const u8 with .len Zig Slices
#define, #ifdef comptime, if on @import("builtin") Zig Comptime
malloc / free An allocator you pass in: gpa.alloc / gpa.free Zig Allocators
Return codes, errno Error unions: !T, try, catch Zig Errors
NULL pointers Optionals: ?*T, checked before use Zig Optionals
goto cleanup defer and errdefer Zig Defer
Undefined behavior Illegal behavior, checked in debug/safe builds Zig Illegal Behavior
Makefile, CMake build.zig Zig Build System
gcc, clang zig cc (Clang, included) Zig as a C Compiler

In C, sharing a function between files takes three pieces: the header with the declaration, the .c file with the code, and an include guard so the header isn’t read twice.

geometry.h
#ifndef GEOMETRY_H
#define GEOMETRY_H
int area(int width, int height);
#endif
geometry.c
#include "geometry.h"
int area(int width, int height) {
return width * height;
}
main.c
#include <stdio.h>
#include "geometry.h"
int main(void) {
printf("area: %d\n", area(3, 4));
return 0;
}

Built with gcc -o app main.c geometry.c, it prints area: 12.

In Zig there are no headers. A file is a module, pub marks what other files may use, and @import gives you the file as a value:

geometry.zig
pub fn area(width: i32, height: i32) i32 {
return width * height;
}
main.zig
const std = @import("std");
const geometry = @import("geometry.zig");
pub fn main() void {
std.debug.print("area: {d}\n", .{geometry.area(3, 4)});
}

Run zig run main.zig and you’ll see:

area: 12

You only name main.zig; Zig follows the imports itself. No declarations to keep in sync with definitions, no include guards, and no order to get right: in Zig, top-level declarations can appear in any order.

A C string is a pointer to bytes that end with a zero. The length isn’t stored anywhere, so strlen walks the whole string to find it, and forgetting the zero is a classic bug.

#include <stdio.h>
#include <string.h>
int main(void) {
const char *name = "Zig";
printf("%s has %zu letters\n", name, strlen(name));
return 0;
}

Output:

Zig has 3 letters

Zig’s everyday string is a slice, []const u8: a pointer and a length, kept together.

const std = @import("std");
pub fn main() void {
const name: []const u8 = "Zig";
std.debug.print("{s} has {d} letters\n", .{ name, name.len });
std.debug.print("the first two: {s}\n", .{name[0..2]});
}

Output:

Zig has 3 letters
the first two: Zi

.len is just a number stored next to the pointer, and indexing a slice is bounds-checked in debug and safe builds. Taking part of a string (name[0..2]) doesn’t copy anything and doesn’t need a zero at the end. When you talk to C, Zig has a type for zero-terminated strings too, [*:0]const u8, and string literals work as both. Zig Strings covers the details.

C macros are text substitution. That’s flexible, and it’s also why this happens:

#include <stdio.h>
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int main(void) {
int i = 5;
int biggest = MAX(i++, 3);
printf("biggest = %d, i = %d\n", biggest, i);
return 0;
}

Output:

biggest = 6, i = 7

i++ was pasted into the macro twice, so it ran twice. Zig has no preprocessor. Instead, a normal function can take a type as a parameter, because types are values known at compile time (comptime):

const std = @import("std");
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
pub fn main() void {
const i: i32 = 5;
std.debug.print("biggest = {d}\n", .{max(i32, i, 3)});
std.debug.print("as floats: {d}\n", .{max(f64, 2.5, 1.5)});
}

Output:

biggest = 5
as floats: 2.5

It’s a real function: type-checked, arguments evaluated once, and it shows up in a debugger. (Zig has no ++ operator at all, by the way. You write i += 1.)

#ifdef goes the same way. Information about the build lives in @import("builtin"), and an if on it is decided while compiling, so the branch that doesn’t apply isn’t even compiled:

const std = @import("std");
const builtin = @import("builtin");
pub fn main() void {
if (builtin.target.os.tag == .windows) {
std.debug.print("hello, Windows\n", .{});
} else {
std.debug.print("hello, {t}\n", .{builtin.target.os.tag});
}
if (builtin.optimize == .debug) std.debug.print("debug build\n", .{});
}

On Linux, in a debug build, you get this.

Output:

hello, linux
debug build

The language reference on comptime shows how far this goes: loops over struct fields, building types, lookup tables computed while compiling.

In C, malloc is one global function. In Zig, there’s no global allocator: a function that needs memory takes an allocator as a parameter, and you choose which one.

#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *squares = malloc(5 * sizeof(int));
if (squares == NULL) return 1;
for (int i = 0; i < 5; i++) squares[i] = i * i;
printf("last square: %d\n", squares[4]);
free(squares);
return 0;
}
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const squares = try gpa.alloc(i32, 5);
defer gpa.free(squares);
for (squares, 0..) |*square, i| square.* = @intCast(i * i);
std.debug.print("last square: {d}\n", .{squares[4]});
}

Output:

last square: 16

Both print last square: 16. The differences:

  • gpa.alloc(i32, 5) takes a type and a count, not a byte size, and returns a slice that knows its length. No sizeof arithmetic to get wrong.
  • Running out of memory is an error, error.OutOfMemory, and try passes it on. You can’t forget the NULL check, because there’s no NULL to check.
  • defer gpa.free(squares) sits right next to the allocation and runs when main ends.
  • init.gpa is a general-purpose allocator that reports leaks in debug builds. Delete the defer line and the program prints a leak report with the line that allocated.

Passing allocators around feels like extra typing at first. It pays off: tests can pass a leak-checking allocator, a short task can use an arena and free everything at once, and you can see from a function’s parameters whether it allocates. Zig Memory starts from the beginning.

C reports most failures with a special return value plus errno:

#include <errno.h>
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *f = fopen("missing.txt", "r");
if (f == NULL) {
printf("could not open: %s\n", strerror(errno));
return 1;
}
fclose(f);
return 0;
}

Output:

could not open: No such file or directory

In Zig, a function that can fail returns an error union: either the value or an error. You can’t use the value without dealing with the error first:

const std = @import("std");
pub fn main(init: std.process.Init) void {
const io = init.io;
const text = std.Io.Dir.cwd().readFileAlloc(io, "missing.txt", init.gpa, .limited(4096)) catch |err| {
std.debug.print("could not open: {t}\n", .{err});
return;
};
defer init.gpa.free(text);
std.debug.print("{s}", .{text});
}

Output:

could not open: FileNotFound

catch |err| handles the error right there; try would pass it to the caller instead. The errors are names like FileNotFound, and the compiler knows the full list a function can return, so a switch on the error can check you covered them all. (The io parameter is how Zig 0.16 and later do all I/O; Zig I/O Interface explains why.)

Undefined behavior becomes checked illegal behavior

Section titled “Undefined behavior becomes checked illegal behavior”

Here’s the off-by-one every C programmer has written:

#include <stdio.h>
int main(void) {
int scores[3] = {10, 20, 30};
int total = 0;
for (int i = 0; i <= 3; i++) total += scores[i];
printf("total = %d\n", total);
return 0;
}

It compiles and runs. On our machine, two runs printed total = 155091516 and total = -902313924: it read whatever was in memory after the array. That’s undefined behavior, and the C standard allows any result at all. (gcc does warn about this one with -O2 -Wall, but only because the index is so obvious.)

The same loop in Zig:

const std = @import("std");
pub fn main() void {
const scores = [_]i32{ 10, 20, 30 };
var total: i32 = 0;
var i: usize = 0;
while (i <= 3) : (i += 1) total += scores[i];
std.debug.print("total = {d}\n", .{total});
}

You’ll see something like:

thread 1753 panic: index out of bounds: index 3, len 3
main.zig:7:46: 0x11e3e1a in main (main.zig)
while (i <= 3) : (i += 1) total += scores[i];
^

Zig calls this illegal behavior. In debug and safe builds it’s checked and stops the program with the exact line, instead of quietly reading garbage. Integer overflow, unwrapping a null optional and reaching unreachable are checked the same way. In fast and small builds the checks are removed for speed, and then it really is undefined, like in C. So you develop and test with checks on and pick per project whether to ship with them. See Zig Build Modes.

A C project usually has a Makefile or a CMakeLists.txt, written in a language of its own, plus a separate compiler and maybe a cross-compiler per target. Zig puts all of that in one place: build.zig is a Zig program, and zig build runs it.

Terminal window
zig init # a new project with build.zig, src/main.zig and src/root.zig
zig build # build it into zig-out/
zig build run # build and run
zig build test # run the tests
zig build -Dtarget=x86_64-windows # the same project for Windows, from any OS

There’s no separate toolchain to install for other targets: the Zig download already contains what it needs, including C standard libraries for many systems. Zig Cross-Compiling shows how far that goes.

You don’t have to rewrite anything to start. Zig can call C functions directly; you declare them with extern and link libc with -lc:

const std = @import("std");
extern "c" fn abs(x: c_int) c_int;
pub fn main() void {
std.debug.print("abs(-7) = {d}\n", .{abs(-7)});
}

Run it with zig run main.zig -lc and you’ll see:

abs(-7) = 7

c_int is C’s int. For a real library, the build system compiles your .c files next to the Zig ones, and the translate-c package turns headers into Zig declarations. One heads-up for readers of older tutorials: @cImport was removed in Zig 0.17, see the 0.17.0 release notes. The C lessons start at Zig and C, then Zig Calling C Libraries and Zig Export to C.

  • Unused variables are errors, not warnings. Same for unused function parameters. Write _ = x; while you’re still writing the code.
  • No hidden integer conversions. Assigning a u32 to a u8 is a compile error (expected type 'u8', found 'u32'). Use @intCast when you know it fits; it’s checked at runtime in debug builds.
  • var that never changes is an error: use const. Zig wants to know what can change.
  • No ++ or --, and for loops go over slices and ranges, not a counter with three parts. A C-style loop is a while with : (i += 1).
  • & binds tighter than ==, the other way round from C, so x & 1 == 0 does what you meant.
  • Pointers can’t be null unless the type says so: ?*T. You check it with if (ptr) |p| or orelse.

Port this C function to Zig. It counts how many times a character appears. Take a slice instead of a zero-terminated string.

int count_char(const char *s, char c) {
int n = 0;
for (; *s != '\0'; s++) {
if (*s == c) n++;
}
return n;
}

Hint: for (text) |ch| walks a slice; there’s no end marker to look for.

Show solution
const std = @import("std");
fn countChar(text: []const u8, c: u8) usize {
var n: usize = 0;
for (text) |ch| {
if (ch == c) n += 1;
}
return n;
}
pub fn main() void {
std.debug.print("{d}\n", .{countChar("banana", 'a')});
}

Output:

3

The loop ends at text.len, so there’s no need for a terminating zero. usize is the natural type for counts and indexes. The standard library already has this one: std.mem.countScalar(u8, "banana", 'a').

Write a function fn repeat(gpa: std.mem.Allocator, c: u8, n: usize) ![]u8 that returns a new string of n copies of c, and call it from main with init.gpa. Free the result.

Hint: gpa.alloc(u8, n) gets the memory, @memset(buf, c) fills it.

Show solution
const std = @import("std");
fn repeat(gpa: std.mem.Allocator, c: u8, n: usize) ![]u8 {
const buf = try gpa.alloc(u8, n);
@memset(buf, c);
return buf;
}
pub fn main(init: std.process.Init) !void {
const line = try repeat(init.gpa, '=', 10);
defer init.gpa.free(line);
std.debug.print("{s}\n", .{line});
}

Output:

==========

The function doesn’t decide where memory comes from; the caller does. The caller also frees it, and in a debug build init.gpa tells you if it doesn’t.

  • @import replaces headers: no declarations to repeat, no include guards.
  • Strings are slices ([]const u8) with a stored length and bounds checks.
  • comptime functions and @import("builtin") replace macros and #ifdef.
  • Memory comes from an allocator you pass in; out of memory is error.OutOfMemory, freed with defer.
  • Error unions replace return codes and errno, and the compiler makes you handle them.
  • C’s undefined behavior is checked illegal behavior in debug/safe builds.
  • build.zig replaces Make/CMake, cross-compiles out of the box, and Zig calls and compiles C directly.

Next up: Zig for Rust Developers, what changes when there’s no borrow checker.

Quick check

1. What replaces a C header file in Zig?
2. In a debug build, what happens when Zig code reads past the end of an array?
3. How does a Zig function tell its caller that it ran out of memory?
4. What do you use in Zig instead of #ifdef _WIN32?