Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect return type for @abs #22340

Closed
ArnaudPare-Vogt opened this issue Dec 28, 2024 · 2 comments
Closed

Incorrect return type for @abs #22340

ArnaudPare-Vogt opened this issue Dec 28, 2024 · 2 comments
Labels
question No questions on the issue tracker, please.

Comments

@ArnaudPare-Vogt
Copy link

Zig Version

0.13.0

Steps to Reproduce and Observed Behavior

This test:

const std = @import("std");
test "abs" {
    const a: i32 = std.crypto.random.int(i32); // random to prevent comptime evaluation
    const b: i32 = @abs(a);
    try std.testing.expect(a == b or a == -b);
}

Fails to compile with:

test.zig:4:20: error: expected type 'i32', found 'u32'
    const b: i32 = @abs(a);
                   ^~~~~~~
test.zig:4:20: note: signed 32-bit int cannot represent all possible unsigned 32-bit values

Expected Behavior

I expect the test to compile.

As far as I can tell, this is because abs returns a u32 when it should return a u31, but I am not super certain about the type system.

@ArnaudPare-Vogt ArnaudPare-Vogt added the bug Observed behavior contradicts documented or intended behavior label Dec 28, 2024
@mlugg
Copy link
Member

mlugg commented Dec 28, 2024

when it should return a u31

Unfortunately, it has to be a u32, because signed integer have a negative range one larger than their positive range. For instance, an i8 can represent the value -128, but a u7 can only represent values up to 127.

This code will work if we accept #3806.

@mlugg mlugg closed this as not planned Won't fix, can't repro, duplicate, stale Dec 28, 2024
@mlugg mlugg added question No questions on the issue tracker, please. and removed bug Observed behavior contradicts documented or intended behavior labels Dec 28, 2024
@ArnaudPare-Vogt
Copy link
Author

For instance, an i8 can represent the value -128, but a u7 can only represent values up to 127.

Damn, I did not think about that, but now the error makes sense.

Thanks for the super fast answer :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question No questions on the issue tracker, please.
Projects
None yet
Development

No branches or pull requests

2 participants