Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is meant by locality of declaration?

I was reading a book and here, a program is given like this -

#include<fstream>
#include<string>
#include<vector>

int main()
{
    string filename; // #1

    cout << "Please enter name of file to open : ";
    cin >> filename;

    if(filename.empty())
    {
        cerr << "Something...";
    }
    ifstream inFile(filename.c_str());  // #2
    if(!inFile)
    {
        cerr<< "Somthing...";
    }
    .
    .
    .
}

And the explanation paragraph says, that, the declaration statements exhibit locality of declaration, Which is explained like this

the declaration statements occur within the locality of the first use of defined objects.

I am very confused with that sentence and I am not able to understand what it actually means. I need an explanation with some example.

like image 604
dukeforever Avatar asked Aug 20 '20 15:08

dukeforever


2 Answers

the declaration statements occur within the locality of the first use of defined objects.

Is another way to say don't declare a thing until you need it. By doing so you bring the declaration to where the object is used and doing so makes it easier to know what that object is.

Imagine you have a function that is 1000 lines long. If you declare all the variables you use in the function at the start, but don't happen to use one of them until line 950, then you have to scroll back 950 lines to figure out what the type of that variable. If you instead declare it on line 949, and use it on line 950, then the information is right there and you don't need to hunt it down as much.

So in your example #2 is declared right before it's used, instead of at the top like #1 is.

like image 191
NathanOliver Avatar answered Oct 12 '22 01:10

NathanOliver


There are several different places in which you can declare variables in a C++ module. For example, one can declare all variables at the beginning of that module, like in the following example:

int MyFunc(int a, int b)
{
    int temp1, temp2, answer;
    temp1 = a + b * 3;
    temp2 = b + a * 3;
    answer = temp1 / temp2;
    return (answer % 2);
}

Alternatively, as in the code you have cited, one could declare each variable immediately before it is first used, as follows:

int MyFunc(int a, int b)
{
    int temp1 = a + b * 3;
    int temp2 = b + a * 3;
    int answer = temp1 / temp2;
    return (answer % 2);
}

Both are valid styles and each will have its supporters and opponents. The latter uses declarations that are in the locality of their first use.

In these simple examples, the difference in styles is really trivial; however, for functions that have (say) 100+ lines of code, using such 'local' declarations can enable a future reader of the code to appreciate the nature of a variable without having to 'scroll back up' to the the start of that function.

like image 41
Adrian Mole Avatar answered Oct 12 '22 01:10

Adrian Mole