Skip to content

Conversation

RalfJung
Copy link
Member

The docs for field-less repr(C) enums are wrong in the sense that they say "the C representation has the size and alignment of the default enum size and alignment for the target platform's C ABI" which implies that there's a single size and alignment (determined by the target) that all repr(C) enums share -- which isn't true. The size of the enum depends on the discriminant values and is intended to mimic what the default C compiler for the target would do with an enum that has the same discriminant values.

Also, it seems worth mentioning the type that the discriminant expressions of an enum are type-checked at: that's isize for all enums expect those with primitive representation.

This PR presupposes that we are going ahead with rust-lang/rust#147017 and documents things as-if the FCW added there was already a hard error. This is mostly because otherwise it's unclear what we should document as the logic before that bug doesn't always match the target's C compiler (see rust-lang/rust#146504).

@rustbot rustbot added the S-waiting-on-review Status: The marked PR is awaiting review from a maintainer label Sep 25, 2025

> [!NOTE]
> The enum representation in C is implementation defined, so this is really a "best guess". In particular, this may be incorrect when the C code of interest is compiled with certain flags.
> For maximum portability, it is always preferred to set the size and alignment explicitly using a [primitive representation](#r-layout.repr.primitive.enum).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the Rust reference but here we are explicitly steering people on how to do an FFI portability thing primarily designed to be compatible with C code. I think we might as well go ahead and note how this can be done in the C source code. Please feel free to disagree, I don't want to scope creep anything unduly.

Suggested change
> For maximum portability, it is always preferred to set the size and alignment explicitly using a [primitive representation](#r-layout.repr.primitive.enum).
> For maximum portability, it is always preferred to set the size and alignment explicitly using a [primitive representation](#r-layout.repr.primitive.enum).
> This can be mimicked in C23 or C++17 using the syntax for enums with fixed underlying types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
S-waiting-on-review Status: The marked PR is awaiting review from a maintainer
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants