马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
int main()
{
int t=1;
{
int t=2;
printf("%d\n",t);
{
t=3;
printf("%d\n",t);
}
printf("%d\n",t);
}
printf("%d\n",t);
return 0;
}
输出是2、3、3、1,为什么不是2、3、2、1呢?
本帖最后由 jackz007 于 2022-1-5 20:24 编辑
本代码在第 5 、7 行分两次定义了同名局部变量 t,所以,在下面的代码中,红色区域和蓝色区域的 t 不是同一个局部变量。
int main()
{
int t=1; // 定义新的局部变量
{
int t=2; // 定义新的局部变量
printf("%d\n",t); // 打印 2
{
t=3; // 为局部变量赋值,并非定义新局部变量
printf("%d\n",t); // 打印 3
}
printf("%d\n",t); // 打印 3
}
printf("%d\n",t); // 打印 1
return 0;
}
这样再看,打印出 2、3、3、1 是不是很合乎逻辑?
下面的代码才会打印 2、3、2、1
int main()
{
int t=1; // 定义新的局部变量
{
int t=2; // 定义新的局部变量
printf("%d\n",t); // 打印 2
{
int t=3; // 定义新的局部变量
printf("%d\n",t); // 打印 3
}
printf("%d\n",t); // 打印 2
}
printf("%d\n",t); // 打印 1
return 0;
}
|