Skip to content

"variable possibly uninitialized" diagnostic points to the wrong control flow construct #121733

Description

@8192K

I tried this code:

fn main() {
    test();
}

fn test() {
    let mut x: i32;
    let a = true;
    
    for i in 0..12 {
        if a {
            x = 5;
        } else {
            return;
        }
        println!("x is initialized in {i}: {x}.");
    }
    
    let z = x;
    println!("{z}");
}

I expected to see this happen: The code compiles and prints the value of z.

Instead, this happened: Compilation failed with the following message

error[E0381]: used binding x is possibly-uninitialized
--> src/main.rs:18:13
|
6 | let mut x: i32;
| ----- binding declared here but left uninitialized
...
12 | } else {
| ------ if the if condition is false and this else arm is executed, x is not initialized
...
18 | let z = x;
| ^ x used here but it is possibly-uninitialized

For more information about this error, try rustc --explain E0381.
error: could not compile playground (bin "playground") due to 1 previous error

I gave a very simple example, the original is much more complex. Here, a is even always true, but the error still appears. In my code, the condition calls a function in each iteration of the loop. Furthermore, the branch it complains about returns, not even reaching the assignment to z below.

To me this seems to be a bug as the code is not asking a ton from the compiler here.

Meta

rustc --version --verbose:

rustc 1.75.0 (82e1608df 2023-12-21)
binary: rustc
commit-hash: 82e1608dfa6e0b5569232559e3d385fea5a93112
commit-date: 2023-12-21
host: aarch64-unknown-linux-gnu
release: 1.75.0
LLVM version: 17.0.6

Happens with 1.76.0 and on nightly as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.D-confusingDiagnostics: Confusing error or lint that should be reworked.S-has-mcveStatus: A Minimal Complete and Verifiable Example has been found for this issueT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions