Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In general the smaller the scope is, the better.</p> <p>There are three main reasons for this rule:</p> <ol> <li><p>Who is reading the code is not distracted trying to understand where the life of the variable will end. Using local variables you can skip over sections of code being sure that in the part skipped nothing you are interested in happened. If instead you use a variable that is not local and reuse it later who is reading must check if any of the code in the middle is using the variable.</p></li> <li><p>When maintaining the program you're free to change the code without worrying that code that follows it may stop working because was dependent on a variable. Suppose you've a loop and is using a variable that is not local and then you change that loop with a call to a function... the risk is that code following the original loop was depending on the value of the index.</p></li> <li><p>Compilers today are quite smart, but sometimes it's confusing even for them if you keep long lifespans for variables. As a result register allocation may suffer from this and the compiled code can be less efficient.</p></li> </ol> <p>If in a function you want to do a step of processing that needs some locals but this step depends on a lot of context and it's not easy to factor it out in a function (because you'd need to pass a lot of parameters) then just open a block for the locals:</p> <pre><code>... code before ... { int local1, local2; ... processing here ... } ... code after ... </code></pre> <p>This is very readable and allows maintaining the smallest possible scope.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload