Zig: Array assignment syntax ignores type name given to it

Created on 27 Oct 2019  路  2Comments  路  Source: ziglang/zig

The following doesn't compile:
var a: [3]f32 = [_]u1{1.5, 10000, 10e100};
with the error,

error: fractional component prevents float value 1.500000 from being casted to type 'u1'

However, the following does compile:
var b: [3]f32 = undefined; b = [3]u1{1.5, 10000, 10e100};
The second line could be [3] followed by literally any type, and the compiler will ignore the given type and treat the following literal as [3]f32 anyway.

Some more valid examples:
b = [3][1][2][3][4]u1{1.5, 10000, 10e100};

const Coordinate = struct {
    x: f32, y: f32
};
...
    b = [3][1][2][3][4]Coordinate{1.5, 10000, 10e100};

To clarify, the values are taken in as f32 and when warned with warn("b: {}, {}, {}\n", b[0], b[1], b[2]);, the following output is given: b: 1.5e+00, 1.0e+04, inf

bug miscompilation stage1

Most helpful comment

test "" {
    var b: [3]f32 = undefined;
    b = [3]u1{ 1.5, 10000, 10e100 };
}

now gives

./test2.zig:3:14: error: expected type '[3]u1', found '[3]f32'
    b = [3]u1{ 1.5, 10000, 10e100 };
             ^

All 2 comments

test "" {
    var b: [3]f32 = undefined;
    b = [3]u1{ 1.5, 10000, 10e100 };
}

now gives

./test2.zig:3:14: error: expected type '[3]u1', found '[3]f32'
    b = [3]u1{ 1.5, 10000, 10e100 };
             ^

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DavidYKay picture DavidYKay  路  3Comments

zimmi picture zimmi  路  3Comments

andrewrk picture andrewrk  路  3Comments

jorangreef picture jorangreef  路  3Comments

bronze1man picture bronze1man  路  3Comments