ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
34.13k stars 2.49k forks source link

Compile error when sizeof used inside ternary operator #18610

Open danielsan901998 opened 8 months ago

danielsan901998 commented 8 months ago

Zig Version

0.12.0-dev.2271+14efbbfd8

Steps to Reproduce and Observed Behavior

Using translate-c with this c function:

void maxsize(int negative){
    static char const min[] = "-9223372036854775808";
    static char const max[] = "9223372036854775807";
    unsigned int const maxdigits = (negative ? sizeof(min): sizeof(max));
}

Generate this error when compiling a test that call the function:

test.zig:68:74: error: value with comptime-only type 'comptime_int' depends on runtime control flow
    const maxdigits: c_uint = @as(c_uint, @bitCast(@as(c_uint, @truncate(if (negative != 0) @sizeOf([21]u8) else @sizeOf([20]u8)))));
                                                                         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.zig:68:87: note: runtime control flow here
    const maxdigits: c_uint = @as(c_uint, @bitCast(@as(c_uint, @truncate(if (negative != 0) @sizeOf([21]u8) else @sizeOf([20]u8)))));
                                                                             ~~~~~~~~~^~~~

Expected Behavior

Successful compilation since when using the result of sizeof it does generate @as(c_int, 21) and it does compile successfully.

ssmid commented 3 months ago

Same applies to switch cases:

const image_count = std.math.clamp(
    switch (actual_present_mode) {
        vk.PRESENT_MODE_IMMEDIATE, vk.PRESENT_MODE_FIFO => 2,
        vk.PRESENT_MODE_MAILBOX => 3,
        else => unreachable,
    },
    1,
    4
);
// ignore that the clamping doesn't make sense here anymore

Error:

error: value with comptime-only type 'comptime_int' depends on runtime control flow
            switch (actual_present_mode) {
            ^~~~~~
src/backend/vulkan.zig:1047:21: note: runtime control flow here
            switch (actual_present_mode) {
                    ^~~~~~~~~~~~~~~~~~~