Skip to content

Unnecessary error sets and casts #2

@Parzival-3141

Description

@Parzival-3141

These functions return unnecessary error unions, as they do not return errors.

pub fn add(a: i32, b: i32) !i32 {
const x = @as(c_int, @intCast(a));
const y = @as(c_int, @intCast(b));
return zmath_ext.add(x, y);
}
pub fn sub(a: i32, b: i32) !i32 {
const x = @as(c_int, @intCast(a));
const y = @as(c_int, @intCast(b));
return zmath_ext.sub(x, y);

Here the readme seems to imply that the error sets are necessary when wrapping C functions or casting integers, which isn't true.

As you can see, we translate the C types to Zig specific types for use in Zig
applications. We cast our input parameters to their C equivalent (c_int) for
the C function's parameters. You'll also notice the return type contains !,
meaning these functions will now return errors. This means within our
application, we'll need to call the function with try.

If you want to show examples of converting C errors to Zig errors, I recommend examples which capture and wrap errno values or do input validation (e.g. detecting division by zero).

Also while the casts to c_int are valid in theory, in practice they're completely unnecessary. My evidence for this is that compiler-rt and the stdlib don't even compile on the 2 supported architectures (avr and msp430) where @bitSizeOf(c_int) != 32, let alone this example program (as of zig version 0.15.2).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions