Member-only story
Software Reliability C++ vs Zig
A tiny comparison of C++ and Zig in terms of building reliable software
I have spent a lot of my life writing C++ code and if there has been one thing that has bothered me about C++ it is just how fragile it is and generally unhelpful in tracking down bugs.
I don’t have time for an exhaustive check here, so here is just the simplest example I could come up with to make a comparison. We are reading a file which doesn’t exist. In C++ we got:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char const *argv[]) {
ifstream file("nonexistingfile.txt");
char buffer[1024];
file.read(buffer, sizeof(buffer));
cout << buffer << endl;
file.close();
return 0;
}
When I run this it gives me absolutely no output. Nothing tells me the file was not there or that anything went wrong.
Let us look at the equivalent program in Zig:
const std = @import("std");
usingnamespace std.fs;
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
const file = try cwd().openFile(
"nonexistingfile.txt",
.{ .read = true },
);
defer file.close();
var buffer: [1024]u8 = undefined;
const size = try file.readAll(buffer[0..]);
try stdout.writeAll(buffer[0..size]);
}
If I run this I actually get a full stack backtrace:
error: FileNotFound
/usr/local/Cellar/zig/0.7.0/lib/zig/std/os.zig:1196:23: 0x10b3ba52e in std.os.openatZ (fileopen)
ENOENT => return error.FileNotFound,
^
/usr/local/Cellar/zig/0.7.0/lib/zig/std/fs.zig:754:13: 0x10b3b857e in std.fs.Dir.openFileZ (fileopen)
try os.openatZ(self.fd, sub_path, os_flags, 0);
^
/usr/local/Cellar/zig/0.7.0/lib/zig/std/fs.zig:687:9: 0x10b3b6c4b in std.fs.Dir.openFile (fileopen)
return self.openFileZ(&path_c, flags);
^
~/Development/Zig/fileopen.zig:8:18: 0x10b3b6810 in main (fileopen)
const file = try cwd().openFile(
I can actually easily jump in and look at the Zig standard library at where things went wrong, or just look at the message in the top which says file not found.
Now, some may argue that I only get this backtrace because I handled the error. Like I wrote try
in front of cwd().openFile
. Except Zig will not let not handle this potential…