Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring pointer to function type, with a function name

Tags:

zig

I found a bit strange feature of Zig when I played with function pointers.

Here is a simple example of a function pointer type:

const std = @import("std");
const print = std.debug.print;

const aFunc = fn (x: i32) void;

fn theFunc(x: i32) void {
    print("have {}\n", .{x});
}

pub fn main() void {
    const f: aFunc = theFunc;
    f(3);
}

This code compiles and runs ok.

Now change it like this, adding a name to the aFunc type definition:

const std = @import("std");
const print = std.debug.print;

const aFunc = fn someFunc (x: i32) void;

fn theFunc(x: i32) void {
    print("have {}\n", .{x});
}

pub fn main() void {
    const f: aFunc = theFunc;
    f(3);
}

This code is also ok, but shouldn't the compiler emit an error or warning about someFunc? This name is useless - when I tried to use it instead of aFunc there was an compilation error.

Compiler version:

$ /opt/zig/zig version
0.10.0-dev.3431+4a4f3c50c

It looks like the zig source parser treats

const aFunc = fn someFunc (x: i32) void;

as if it is function definition, but silently drops someFunc.

like image 209
dee0xeed Avatar asked Aug 13 '26 06:08

dee0xeed


1 Answers

This was a bug in the Zig compiler. It was fixed in https://github.com/ziglang/zig/commit/fc213e2d61c9ae6e643ddebf502c699abe4055e8 and released in v0.11.0.

like image 85
P.T. Avatar answered Aug 15 '26 20:08

P.T.