Skip to content

Ternary if works incorrectly inside tuple #13583

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

Closed
wvlab opened this issue Nov 18, 2022 · 1 comment
Closed

Ternary if works incorrectly inside tuple #13583

wvlab opened this issue Nov 18, 2022 · 1 comment
Labels
bug Observed behavior contradicts documented or intended behavior

Comments

@wvlab
Copy link

wvlab commented Nov 18, 2022

Zig Version

0.9.1-2

Steps to Reproduce and Observed Behavior

const std = @import("std");
const testing = @import("std").testing;
const RndGen = std.rand.DefaultPrng;

test "anonymous struct ternary if" {
    var list = std.ArrayList(u8).init(testing.allocator);
    defer list.deinit();
   
    var rnd = RndGen.init(2).random();
    var n: usize = 0;

    while (rnd.int(i8) != 5) {
        n += 1;
    }
    std.debug.print("\nn: {}\n", .{n});
    
    var sign = "-";
    if (@mod(n, 2) == 1) {
        sign = "+";
    }

    try list.writer().print(
        "{s}",
        .{ if (@mod(n, 2) == 1) "+" else "-"},
    );
    testing.expect(std.mem.eql(u8, list.items, sign)) catch |err| {
        std.debug.print("\ngot: {s}\n", .{list.items});
        std.debug.print("expected: {s}\n", .{sign});
        return err;
    };
 
    sign = "-";
    if (@mod(n - 1, 2) == 1) {
        sign = "+";
    }

    try list.writer().print(
        "{s}",
        .{ if (@mod(n - 1, 2) == 1) "+" else "-"},
    );
    testing.expect(std.mem.eql(u8, list.items, sign)) catch |err| {
        std.debug.print("got: {s}\nexpected: {s}", .{list.items, sign});
        return err;
    };
}

Expected Behavior

I expected to have runtime ternary if inside tuple or at least compilation error, nothing happened and it returned value if condition was true. I think it can easily cause bugs in some projects

@wvlab wvlab added the bug Observed behavior contradicts documented or intended behavior label Nov 18, 2022
@Vexu
Copy link
Member

Vexu commented Nov 18, 2022

Duplicate of #3882, fixed in self-hosted which ships by default in the latest release 0.10.0

@Vexu Vexu closed this as completed Nov 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Observed behavior contradicts documented or intended behavior
Projects
None yet
Development

No branches or pull requests

2 participants