C Ansi内存分配关闭

Rag*_*azs 2 c scope

我有这个东西:

用.编译 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在内部条件中声明的所有变量都将关闭到该范围?

Uch*_*chi 6

当然它必须抛出错误.

{}大括号被用来定义一个块赋予该块的新的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-whileswitch构建他们使用时定义为他们每个人一个新的范围.

这是一个良好的机制,可以在其中限制的知名度data成员在C其中definition/declaration的变量中遇到的任何可执行语句之前只在一个块的起始允许的.