Zig和C格式化输出区别

44 阅读1分钟

Zig和C格式化输出的最主要区别是:

C的格式化输出是运行时检查或无检查,类型不匹配会导致未定义行为。

而Zig是编译期强类型检查,格式化符与参数类型不匹配会直接编译失败。

如下面的代码:

#include <stdio.h>
int main() {
    printf("num: %d\n", "hello"); 
    return 0;
}

现代C编译器(GCC/Clang)会对格式化符和参数类型不匹配做警告/检查。比如编译上述代码可能会提示

warning: format specifies type 'int' but the argument has type 'char *' [-Wformat]

但是这是警告而非错误,程序依然可以编译成功,但输出的值是不可预料的,即该行为是未定义的。并且还可以通过 -Wno-format屏蔽该警告。

而下述Zig代码

const std = @import("std");
pub fn main() void {
    std.debug.print("num: {d}\n", .{"hello"}); 
    // 
}

会报编译错误

error: invalid format string 'd' for type '*const [5:0]u8'
    @compileError("invalid format string '" ++ fmt ++ "' for type '" ++ @typeName(@TypeOf(value)) ++ "'");

程序并不能成功编译。