Skip to content

Floats and compile time ints #12873

@CarlOlson

Description

@CarlOlson

Zig Version

0.9.1

Steps to Reproduce

const std = @import("std");

test {
    // Case 1: Pass
    var i: i32 = 1 / 3;
    try std.testing.expectEqual(@as(i32, 0), i);

    // Case 2: Fail
    var f: f32 = 1 / 3;
    try std.testing.expectEqual(@as(f32, 1.0 / 3.0), f);

    // Case 3: Compile Error
    var one: i32 = 1;
    var three: i32 = 3;
    _ = one / three;

   // Case 4: Compile Error
   var f2 = 1.0 / 3;
   _ = f2;
}

Expected Behavior

I expect case 1 to be a compile error.

I expect either a compile error or f == 1.0 / 3.0 for case 2.

The current behavior allows for errors to be added easily and can it be hard to track down the cause. I was getting a chain of NaN.

Actual Behavior

Case 2

Test [0/1] test ""... expected 3.33333343e-01, found 0.0e+00
Test [1/1] test ""... FAIL (TestExpectedEqual)
.../zig-linux-x86_64-0.9.1/lib/std/testing.zig:79:17: 0x215b61 in std.testing.expectEqual (test)
                return error.TestExpectedEqual;
                ^
.../src/test.zig:8:5: 0x21550b in test "" (test)
    try std.testing.expectEqual(@as(f32, 1.0 / 3.0), f);
    ^
0 passed; 0 skipped; 1 failed.

Case 3

./src/test.zig:12:13: error: division with 'i32' and 'i32': signed integers must use @divTrunc, @divFloor, or @divExact
    _ = one / three;

Case 4

./src/test.zig:13:19: error: float value 1.000000 cannot be coerced to type 'comptime_int'
    var f2: f32 = 1.0 / 3;

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behavior

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions