What is meant by locality of declaration?

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.


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.