gpt4 book ai didi

C Ansi 内存分配闭包

转载 作者:行者123 更新时间:2023-12-04 10:37:18 25 4
gpt4 key购买 nike

我有这个东西:

使用 gcc a.c -o a 编译

// a.c
int main() {
int a;
if (1) {
int b;
}
b = 2;
}

在控制台中我会遇到以下错误:

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

C Ansi 中在条件内声明的所有变量都将在该范围内关闭?

最佳答案

当然它必须抛出一个错误。

{} 大括号用于定义一个 block ,它为 block 提供了一个新的作用域。因此,在范围内定义或创建的所有内容都无法在该范围外访问。

但是如果该 block 包含其他一些 block ,则您可以访问该 block 中外部作用域的成员。

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;
}

并且,由于 {}if 中使用,for,while, do-whileswitch 结构在使用时为它们各自定义了一个新范围。

这是一个很好的机制,您可以在 C 中限制 data 成员的可见性,其中变量的 definition/declaration 只是允许在遇到任何可执行语句之前的 block 开头。

关于C Ansi 内存分配闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18191536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com