报关地点是什么意思?

What is meant by locality of declaration?

我正在看书,这里给出了这样的程序-

#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...";
    }
    .
    .
    .
}

解释段落说,声明语句显示声明的位置,解释如下

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

我对那句话很困惑,无法理解它的实际含义。我需要一些例子的解释。

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

另一种说法是在需要之前不要声明。通过这样做,您可以将声明带到使用对象的地方,这样做可以更容易地了解该对象是什么。

假设您有一个 1000 行长的函数。如果您在一开始就声明了您在函数中使用的所有变量,但直到第 950 行才碰巧使用其中一个变量,那么您必须向后滚动 950 行才能确定该变量的类型。如果您改为在第 949 行声明它,并在第 950 行使用它,那么信息就在那里,您不需要那么多地寻找它。

因此在您的示例中,#2 是在使用之前声明的,而不是像 #1 那样在顶部声明。

在 C++ 模块中有几个不同的地方可以声明变量。例如,可以在该模块的开头声明 all 变量,如下例所示:

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

或者,在您引用的代码中,可以在每个变量首次使用之前立即声明它,如下所示:

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

两者都是有效的风格,各有其支持者和反对者。后者使用 首次使用地点的声明

在这些简单的例子中,风格上的差异实在是微不足道;但是,对于具有(比如说)100 多行代码的函数,使用这样的 'local' 声明可以使代码的未来 reader 能够理解变量的性质,而不必 'scroll back up'到该函数的开头。