我有这个东西:
用.编译 gcc a.c -o a
// a.c
int main() {
int a;
if (1) {
int b;
}
b = 2;
}
Run Code Online (Sandbox Code Playgroud)
在控制台中我将有以下错误:
a.c:7:4: error: ‘b’ undeclared (first use in this function)
a.c:7:4: note: each undeclared identifier is reported only once for each function it appears in
Run Code Online (Sandbox Code Playgroud)
C Ansi在内部条件中声明的所有变量都将关闭到该范围?
当然它必须抛出错误.
的{和}大括号被用来定义一个块赋予该块的新的scope.因此,在范围之外定义或创建的所有内容都无法在该范围之外访问.
但是,如果该块包含其他一些块,则可以访问块中外部作用域的成员.
即
int main()
{
int a;
{
int b;
{
int c;
b = c; // `b` is accessible in this innermost scope.
a = c; // `a` is also accessible.
}
// b = c; `c` is not accessible in this scope as it is not visible to the 2nd block
b = a; // `a` is visible in this scope because the outermost block encloses the 2nd block.
}
// a = b; outermost block doesn't know about the definition of `b`.
// a = c; obviously it is not accessible.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
而且,由于{}在使用if的,for,while,do-while和switch构建他们使用时定义为他们每个人一个新的范围.
这是一个良好的机制,可以在其中限制的知名度data成员在C其中definition/declaration的变量中遇到的任何可执行语句之前只在一个块的起始允许的.
| 归档时间: |
|
| 查看次数: |
278 次 |
| 最近记录: |