Giter VIP home page Giter VIP logo

Comments (3)

mlugg avatar mlugg commented on May 29, 2024

Yes, I think it's accurate to say that initializing a packed union with a small field leaves the remaining bits undefined, so that code snippet just has a bug. That said, I'll wait for @andrewrk to confirm the intended behavior before closing.

from zig.

andrewrk avatar andrewrk commented on May 29, 2024

Thanks for the report.

This is indeed working as designed given how unions work in zig: only the active field has a defined value, and the bitcast therefore accesses undefined memory, making cell_int have undefined bits, or be fully undefined, depending on the resolution of #19634.

Based on the recent guidance that I wrote on struct field initialization, I would recommend this instead:

const Cell = packed struct(u64) {
    content: packed union {
        a: u21,
        b: u22,
    },
    _padding: u42,

    const init: Cell = @bitCast(@as(u64, 0));
};
test {
    const cell = Cell.init;
    const cell_int: u64 = @bitCast(cell);
    try @import("std").testing.expectEqual(@as(u64, 0), cell_int);
}

This code snippet should be considered when evaluating #19634, but I don't think it needs to remain open as a bug or a proposal.

from zig.

mitchellh avatar mitchellh commented on May 29, 2024

Thanks, that's exactly what I ended up doing.

from zig.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.