Declaring variables inside or outside of a loop

前端 未结 20 2040
后悔当初
后悔当初 2020-11-22 01:59

Why does the following work fine?

String str;
while (condition) {
    str = calculateStr();
    .....
}

But this one is said to be dangerou

相关标签:
20条回答
  • 2020-11-22 02:58

    if you want to use str outside looop also; declare it outside. otherwise, 2nd version is fine.

    0 讨论(0)
  • 2020-11-22 02:58

    Variables should be declared as close to where they are used as possible.

    It makes RAII (Resource Acquisition Is Initialization) easier.

    It keeps the scope of the variable tight. This lets the optimizer work better.

    0 讨论(0)
提交回复
热议问题