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…