openlang

Loop variable lifetime

Consider this rather silly snippet:

3.times do |round|
    cell = uninitialized Int32
    if cell == 60
        puts "cell = 60, round = #{round}"
        puts " (by chance!)" if round == 0
    end
    cell = 60
end

Does every iteration create cell again, coincidentally placing it at the address used by cell on the preceding iteration (which would explain its value of 60 on the third pass)?

Or does one variable persist across all three iterations, so that I can rely on that?

The conversation continues 1

Follow the reasoning
  1. Permalink

    With uninitialized, the variable refers to memory containing whichever data happens to be there already. That's precisely why uninitialized exists: it neither clears that memory nor assigns an initial default value.

    Here, cell coincidentally resides at an identical address on every iteration. The way the stack operates probably makes this behaviour consistently observable, but depending on it would be a mistake. A single variable isn't persisting from one iteration to another.

    If it chooses, the compiler / code generator may rearrange where things live.

Other sides of the same question

  1. Delaying a cleanup block's mutable borrow until it actually runs

    What would be a way for me to write a panic-safe mecanism in Rust that behaves similarly to Java's try { ... } finally { ...…

    Replies 2Latest activity rust
  2. Inputting character arrays through pointers

    Whenever I attempt keyboard input into some char arrays, my program ends up crashing. What's a straightforward way of reading…

    Replies 2Latest activity c
  3. Can an input function avoid relying on global variables?

    I'd like a function to process what a user enters, filter it, and return the resulting string to whichever function called it…

    Replies 2Latest activity c