Formatting int does add a + sign

Why does this

    const x: i32 = 42;
    lib.io.debugprint("{:>6}\n", .{ x });

output

   +42

instead of this?

    42

Additional riddle: why can’t the compiler parse numbers with a + in front?

const ar: [2]i32 = .{
    -42, // error: expected expression, found '+'
    +42,
};

Relevant discussions/issues:

There’s an open PR that would get rid of the leading +.

Zig doesn’t have a unary + operator (see the list of operators)

Thanks. I will read these.

(My simple mind thought: “If -42 is legal for declaring a signed int, why +42 not?”)

I think it might be related to how zig parses expressions.

I believe the rationale is that unary + is a no-op and thus violates the zen of “only one obvious way to do things”.

Often I wish that was true :slight_smile: Always these choices choices…

If we go so far we could even say unary - is redundant because one could “just” do this:

a + -b == a + (0 - b)

Of course this isn’t really practical.


But sometimes a unary plus is indeed nice for clarity and formatting

1 Like

Yup. I miss these more than I care to admit. For example, for lining up matrix initializers.

3 Likes

Same here..

I mean, at least unary - often has a direct counterpart in instruction sets, i.e. CPUs seem to generally have a dedicated negation instruction[1]. Not that it’s a super strong argument, but it’s something.

Also, obvious does heavy lifting in the zen – yes, Zig does provide multiple ways to do things (try vs catch |e| return e; .? vs orelse unreachable; const a = T{}; vs const a: T = .{}[2]), but the emphasis is on having the preferred alternatives be as obvious as possible. I’d argue that the obvious way to do nothing is exclusively writing nothing, while the obvious way to negate is (at least to me) to use a unary -.

Hey, I don’t disagree, though I think maybe having zig fmt embrace alignment, as proposed would alleviate this issue more elegantly?


  1. Though, admittedly, I just looked in the ARMv7 reference that I have handy and while there is a dedicated NEG instruction described, they state that it is a pre-UAL synonym for RSB with an immediate value of 0, which is in a sense exactly what you describe. ↩︎

  2. That one is on its way out ↩︎

3 Likes

I also think that formatted alignment with - and nothing is visually more distinct than having terms that begin with either - or +

1 Like