[Simple quiz]: Does this program print anything?

A demo of a recent careless accident. :smiley:

const std = @import("std");

fn foo(n: i32) void {
    if (n == 0) return

    if (n < 0) std.debug.print("< 0 \n", .{})
    else std.debug.print("> 0 \n", .{});
}

pub fn main() void {
	foo(0);
}

4 Likes

Outputs > 0 due to missing semicolon on return. It’s kinda sneaky for sure though.

zig fmt makes the problem clearer:

const std = @import("std");

fn foo(n: i32) void {
    if (n == 0) return if (n < 0) std.debug.print("< 0 \n", .{}) else std.debug.print("> 0 \n", .{});
}

pub fn main() void {
    foo(0);
}

One of the reasons why I have fmt on save enabled.

9 Likes

Interesting example though, as zig fmt won’t help much if the second if has a comment.

1 Like

Even then it helps:

 if (n == 0) return if (n < 0) std.debug.print("< 0 \n", .{}) // something
 else std.debug.print("> 0 \n", .{});

Relevant accepted proposal:

2 Likes

Try with this (zig fmt does nothing for me here):

fn foo(n: i32) void {
    if (n == 0) return

    // Some comment
    if (n < 0) std.debug.print("< 0 \n", .{}) else std.debug.print("> 0 \n", .{});
}
1 Like

After saving, an error is immediately displayed in the editor:
Expected expression, found β€˜;’

I think that should be enough to recognize that something is wrong.

No error in my editor using zls and also the program compiles just fine: The Zig Pastebin

Was my bad, made a copy/paste error. Indeed, then it’s not easy to see the error immediately. :slightly_frowning_face:

no sympathy for those who forsake zig fmt

6 Likes