#why doesn't `const x: u32 = <u16> * <u16>` automatically widen to u32? (0.11.0)

1 messages · Page 1 of 1 (latest)

fallow peak
#
test "widening" {
    const a: u16 = 1024;
    const b: u16 = 512;

    const c: u32 = a * b;
    try std.testing.expect(c == 1024 * 512);
}

Yields:

error: overflow of integer type 'u16' with value '524288'
    const c: u32 = a * b;
                   ~~^~~

To get it to work I need to do something like:

const aa: u32 = a;
const bb: u32 = b;
const c: u32 = a * b;

Which seems overly verbose. Is this a bug or intended behavior?

surreal lion
#

you can also do it this way.

test "widening" {
    const a: u16 = 1024;
    const b: u16 = 512;

    const c: u32 = @as(u32, a) * b;
    try std.testing.expect(c == 1024 * 512);
}
#

i believe this is intended but not sure where to point you to for details

#

i don't see anything relevant to this there at a glance

lucid garnet
#

are you looking for std.math.mulWide

fallow peak
#

I worked around it, but I found it very surprising that this lead to a runtime panic

#

IMO if widening doesn't happen during arithmetic then my original test should be a compiler error