曾经我认为这两个词意思相同,但是在阅读更多相关内容后,我仍然不清楚它们之间的区别。难道本地作用域有时不是指函数作用域吗?而且什么意思是只有标签具有函数作用域?
void doSomething()
{ <-------
{ <---- |
| |
int a; Local Scope Function Scope
| |
} <---- |
} <-------
函数作用域在外层的 {}
之间。
局部作用域在内层的 {}
之间。
请注意,任何由 {}
创建的作用域都可以被称为局部作用域,而函数体开头的 {}
则创建了函数作用域。因此,有时局部作用域和函数作用域可能相同。
什么意思,只有标签具有函数作用域?
标签
只是紧跟着冒号的标识符。 标记语句用作 goto
语句的目标。 标签可以在它们出现的函数中的任何地方使用,但不能在函数体外引用。 因此,它们被认为具有函数作用域。
代码示例:
int doSomething(int x, int y, int z)
{
label: x += (y + z); /* label has function scope*/
if (x > 1)
goto label;
}
int doSomethingMore(int a, int b, int c)
{
if (a > 1)
goto label; /* illegal jump to undefined label */
}
本地作用域是指在一个 { 和它的闭合 } 之间的区域。函数作用域是指在函数开头的 { 和结束的 } 之间的区域,其中可能包含更多的“本地”作用域。标签在定义它的整个函数中都是可见的,例如:
int f( int a )
{
int b = 8;
if ( a > 14 )
{
int c = 50;
label:
return c - a - b;
}
if ( a > 7 ) goto label;
return -99;
}
int c
在其封闭块之外不可见。标签在其封闭块之外可见,但仅限于函数范围。
void foo(int a) {
if (a == 0) goto here; // okay -- 'here' is inside this function
printf("a is not zero\n");
goto there; // not okay -- 'there' is not inside this function
here:
return;
}
void bar(int b) {
if (b == 0) goto there; // okay -- 'there' is in this function
printf("b is not zero\n");
there:
return;
}
不想引起争议,但标签的使用范围可能不会经常出现。标签主要在使用goto
语句时非常有用,但这种情况很少发生,即使您选择使用goto
,您也可能不会尝试跳转到另一个函数。
void f(int a) try {
// function body
} catch(...) {
// catch block
}
bool m[3][3];
void f1()
{
int i;
// redefining a variable with the same name in the same scope isn't possible
//int i; //error C2086: 'int i' : redefinition
}
void f2()
{
int i; // ok, same name as the i in f1(), different function scope.
{
int i; // ok, same name as the i above, but different local scope.
}
// the scope if the following i is local to the for loop, so it's ok, too.
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (m[i][j])
goto loopExit;
}
}
loopExit:
std::cout << "done checking m";
// redefining a label with the same name in the same function isn't possible
// loopExit:; // error C2045: 'loopExit' : label redefined
}
void f3()
{
loopExit:; // ok, same label name as in f2(), but different function scope
}