如果在块中定义了变量,它是仅存在于块中还是整个程序中?例如
main()
{
int j=5;
{
int i=10
printf("%d",i);
}
printf("%d , %d ",i,j);
}
Run Code Online (Sandbox Code Playgroud)
它有效吗?
main()
{
int j=5, *k;
{
int i=10
printf("%d",i);
}
k=&i
printf("%d , %d ",*k,j);
}
Run Code Online (Sandbox Code Playgroud)
因为变量保留在内存中从它的声明点到函数退出点?
R S*_*hko 11
非全局变量的作用域仅限于它定义的块.此外,对于自动变量,一旦块结束,变量的生命周期就结束了.
考虑这个愚蠢的例子:
void doit()
{
int *ps;
int *pa;
{
static int s = 1;
int a = 2;
ps = &s;
pa = &a;
}
// cannot access a or s here because they are out of scope
// *ps is okay because s is static so it's lifetime is not over
// *pa is not okay because a's lifetime ends at the end of the block
}
Run Code Online (Sandbox Code Playgroud)
您的第二个printf行将无法编译,因为i
它不在范围内.