user3689849
user3689849

Reputation: 521

Pro and cons of restrict the scope of variable

From the book "The C++ programming language 4 edition", the author like to restrict the scope of the variable. It is in the chapter "3.2.1.3 Initializing Containers"

The code is:

Vector read(istream& is)
{
    Vector v;
    for (double d; is>>d;) // read floating-point values into d
    v.push_back(d); // add d to v
    return v;
}

He said

I used a for-statement rather than the more conventional while-statement to keep the scope of d limited to the loop.

What are the advantages of doing this?

Upvotes: 1

Views: 374

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106096

Restricting scope means:

  • RAII types (those managing resources like file or network I/O handles, memory, locks for threading etc. and releasing those resources in their destructors) have their destructor's cleanup code run earlier rather than later, optimising duration of resource use with potential flow-on benefits to their own execution and that of other programs

  • later code can reuse the same identifier for another purpose... why keep dreaming up variable names if they're serving the same logical purpose in different loops, but happen to differ in type?

  • there's no risk of attempted reuse of the variable forgetting to reset its value after an earlier unrelated use

  • the programmer reading the code doesn't need to keep it in mind when analysing the code after the scope it's used in; all up, there's a lot less cross-referencing and searching needed to confidently understand the code

  • you can use auto in the various contexts of use to avoid errors like this...

 

    float x;
    for (x = my_floats.first(); x < 10; x = my_floats.next())
        ...

    for (x = my_doubles.first(); x < 10; x = my_doubles.next())
        ... oops... getting float precision when double available...
  • if as your code evolves you want to change the variable name and/or type to reflect its use, you can more easily do so in a localised way without the name becoming misleading through other code, or the type becoming inappropriate (perhaps silently degrading results as with the float/double example above); even without a fancy IDE with "refactoring" support, compiler errors can help you make the change accurately in a local scope without doing a (more error-prone) global search and replace...

Upvotes: 6

utnapistim
utnapistim

Reputation: 27365

On top of @TonyD's answer:

  • ideally, you should have variables declared as close as possible to the place you are using them.

    This makes the code faster when not reaching the execution branch the value is used on.

    Example:

    void f()
    {
        std::string s{ "will be interesting later" ); // some local variable that
                                                      // could have been declared
                                                      // lower in the code
        void g(); // may throw
        use(s);
    }
    

    Depending on the size of s, allocating it may be an expensive operation. If g throws though, s will not be needed, and the resources allocated for it will have been wasted. Allocating s before calling g also means that g will be run with less resources available (considering the capabilities of computers these days, this probably doesn't matter practically, in most cases).

  • having declarations close to where you use them means scrolling to see type definitions is unnecessary. Declarations for which you have to scroll up to see, are "out of sight" (and thus, out of mind :) ).

  • editing/manual refactoring. Consider wanting to extract the call to use to a different function: if the code above didn't have the call to g in between, you could just copy & paste. This way, you either paste the entire block, then remove the call to g, or copy twice (for defining s and for calling use).

Upvotes: 3

OshoParth
OshoParth

Reputation: 1552

The simplest reason behind declaring and initializing the variable i in the scope of for loop is to keep the code simple to debug and understand and to prevent unnecessary use of memory by the counter variables throughout the program execution.ie

In the Following code where the variable i is out of the scope of for loop can effect the code outside for loop too. However it was intended to be used only as counter variable for the loop. This this style should be adopted only and only if you want to preserve and use value of loop counter beyond the scope of loop.

int main()
{
    int bigNumber = 10;
    int i;
    for(i = 0; i != bigNumber; ++i){
       cout<<i;
       if(i==2)
       break;
    }
    cout<<"loop terminated at"<<i;
    return 0;
}

And as far as the second style is considered it makes sure that the variable i has its role and value restricted only till the scope of the loop. In the code given below you would not be able to use the counter variable beyond the scope of loop resulting in error. This helps in preventing the unnecessary memory use by the counter variables.

int main()
{
    int bigNumber = 10;
    for(int i = 0; i != bigNumber; ++i){
        cout<<i; 
    }
   cout<<i;
   return 0;
}

Upvotes: 1

Related Questions