Skip to content

repr(C) on an enum accepts discriminants that do not fit into the default C enum size #124403

Open
@RalfJung

Description

@RalfJung

Example:

#[repr(C)]
enum OverflowingEnum {
    A = 1111111111111111111,
}
enum overflowing_enum {
    OVERFLOWING_ENUM_A = 1111111111111111111,
};

Rust currently gives size_of::<OverflowingEnum>() = 8. MSVC gives sizeof(enum overflowing_enum) = 4. Additionally, Rust gives OverflowingEnum::A as usize = 1111111111111111111 and MSVC gives OVERFLOWING_ENUM_A = 734294471.

This should probably be a hard error (forward compatibility lint). The nomicon currently states

repr(C) is equivalent to one of repr(u*) (see the next section) for fieldless enums. The chosen size is the default enum size for the target platform's C application binary interface (ABI).

and the reference currently states

For field-less enums, the C representation has the size and alignment of the default enum size and alignment for the target platform's C ABI.

The nomicon is clearly wrong here: #[repr(c_int)] on the enum would fail to compile (where c_int is the correct primitive) (because of the overflowing literal). I think erroring (forward compatibility linting) and pointing the user to use #[repr(u64)] in this case makes sense.

(Summary by @CAD97)

@CAD97 this should error on all targets, not just MSVC, I assume? What do non-MSVC C compilers do with such an enum?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-FFIArea: Foreign function interface (FFI)A-enumArea: Enums (discriminated unions, or more generally ADTs (algebraic data types))A-reprArea: the `#[repr(stuff)]` attributeO-windowsOperating system: WindowsO-windows-msvcToolchain: MSVC, Operating system: Windows

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions