Should variable declarations always be placed outside of a loop?

前端 未结 6 1410
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 15:39

Is it better to declare a variable used in a loop outside of the loop rather then inside? Sometimes I see examples where a variable is declared inside the loop. Does this ef

6条回答
  •  佛祖请我去吃肉
    2020-12-20 15:58

    No, it wouldn't be more efficient. However, I'd rewrite it this way which happens to declare it outside the loop anyway:

    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, read);
    }
    

    I'm not generally a fan of using side-effects in conditions, but effectively the Read method is giving you two bits of data: whether or not you've reached the end of the stream, and how much you've read. The while loop is now saying, "While we've managed to read some data... copy it."

    It's a little bit like using int.TryParse:

    if (int.TryParse(text, out value))
    {
        // Use value
    }
    

    Again you're using a side-effect of calling the method in the condition. As I say, I don't make a habit out of doing this except for this particular pattern, when you're dealing with a method returning two bits of data.

    The same thing comes up reading lines from a TextReader:

    string line;
    while ((line = reader.ReadLine()) != null)
    {
        ...
    }
    

    To go back to your original question: if a variable is going to be initialized in every iteration of a loop and it's only used within the body of the loop, I'd almost always declare it within the loop. One minor exception here is if the variable is being captured by an anonymous function - at that point it will make a difference in behaviour, and I'd pick whichever form gave me the desired behaviour... but that's almost always the "declare inside" form anyway.

    EDIT: When it comes to scoping, the code above does indeed leave the variable in a larger scope than it needs to be... but I believe it makes the loop clearer. You can always address this by introducing a new scope if you care to:

    {
        int read;
        while (...)
        {
        }
    }
    

提交回复
热议问题