Skip to content

Should C-style enums silently overflow? #23030

Closed
@pnkfelix

Description

@pnkfelix

Spawned off of a note from PR #22532 on commit 1246d40

The following program:

#[repr(usize)]
enum Foo {
    A = 0xffffffffffffffff_usize,
    B,
    C
}

fn main() {
    println!("Hello World: {:x}", Foo::A as usize);
    println!("Hello World: {:x}", Foo::B as usize);
    println!("Hello World: {:x}", Foo::C as usize);
}

compiles and prints:

Hello World: ffffffffffffffff
Hello World: 0
Hello World: 1

My personal preference would be for a compiler error due to the implicit overflow, with a note saying that the programmer should explicitly assign some value to Foo::B. (And thus they can opt into the current behavior by assigning it B = 0,; then Foo::C would continue to be assigned 1 as today.)

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions