Skip to content

allow align(0) on struct fields #3802

Closed
@andrewrk

Description

@andrewrk

This is a sister issue to #3133. Packed structs offer a way to explicitly provide the layout of a struct in memory. But non-packed structs also can offer something powerful: the ability to say that you do not need a field to be aligned to a byte boundary.

const S = struct {
    a: bool align(0),
    b: u8,
    c: bool align(0),
    d: bool align(0),
    e: bool align(0),
};

Because structs do not guarantee field order, Zig is allowed to put a, c, d, and e fields into 1 byte, making the entire struct only 2 bytes, rather than 5.

The compromise here is that pointers to align(0) fields have pointer metadata in the type that prevents it from being coerced to a "normal" pointer for that type. This the same thing as taking a pointer of a non-byte-aligned packed struct field.

However this would be quite useful for flags, where one typically does not need a pointer to an individual flag. Rather, one typically accesses flags from a base pointer, which would work just fine with align(0) flag fields.

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions