Skip to content

Bad suggestion for overflowing hex literal in signed operation #53628

Open
@tspiteri

Description

@tspiteri

Code:

pub fn flip_msb(a: i32) -> i32 {
    a ^ 0x8000_0000
}

Diagnostic:

warning: literal out of range for i32
 --> src/lib.rs:2:9
  |
2 |     a ^ 0x8000_0000
  |         ^^^^^^^^^^^
  |
  = note: #[warn(overflowing_literals)] on by default
  = note: the literal `0x8000_0000` (decimal `2147483648`) does not fit into an `i32` and will become `-2147483648i32`
  = help: consider using `u32` instead

In this case using u32 is not an option (you could use a u32 literal and cast to i32, but that's not ideal). A better suggestion in this case would be to use -0x8000_0000 instead.

This issue is, I think, more relevant to hex (or other non-decimal) representations, as for example format!("{:#x}", i32::MIN) would produce 0x80000000, which could lead someone to think that that is a valid warning-free i32 literal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions