Strange behavior in nested while loops


#1

Can somebody explain what is going on in the following code; is it a bug or a language feature that the loops appear to exit early?

fn main() {
    let mut y = 0.0;
    let mut x = 0.0;
    while y < 4.0 {
        while x < 4.0 {
            println!("{}, {}", x, y);
            x+=1.0;
        }
        y+=1.0;
    }
    println!("{}, {}", x, y);
}

results in this output

0, 0
1, 0
2, 0
3, 0
4, 4

https://play.rust-lang.org/?gist=0eff20c7654539063ee2faa09f38bed6&version=stable&mode=debug


#2

Move the initialization of x inside the outer while loop.


#3

What exactly makes you think it’s exiting early?


#4

0, 0
1, 0
2, 0
3, 0
4, 4

The code is doing what have to do. 3 println after that increases the y four times (without println anything), and the last println


#5

Doh; thanks :slight_smile: