c - 关于块范围链接,没有错误,没有警告,但结果很惊讶,我不知道为什么
问题描述
#include <stdio.h>
int main(void) {
int count = 22;
{
int count = count * 2;
printf("inner: %d\n", count);
}
printf("outer: %d\n", count);
return 0;
}
输出:
inner: 65532
outer: 22
输出很惊讶,我不知道为什么。
编辑:编译方法:gcc test.c
解决方案
int count = count * 2;
in count * 2
count is not initialized because it is the inner count, not the outer count as you probably supposed
so your code is equivalent to
int main(void) {
int outer_count = 22;
{
int inner_count = inner_count * 2;
printf("inner: %d\n", inner_count);
}
printf("outer: %d\n", outer_count);
return 0;
}
but not to
int main(void) {
int outer_count = 22;
{
int inner_count = outer_count * 2;
printf("inner: %d\n", inner_count);
}
printf("outer: %d\n", outer_count);
return 0;
}
no warning
I do not know what compiler and options you use, but :
pi@raspberrypi:/tmp $ gcc -Wall c.c
c.c: In function ‘main’:
c.c:6:9: warning: ‘count’ is used uninitialized in this function [-Wuninitialized]
int count = count * 2;
^~~~~
pi@raspberrypi:/tmp $
推荐阅读
- excel - 是否可以在 IF/ELSE 语句的 FALSE 上运行新的多级公式?
- c++ - 在 c++ 中使用 System 打开程序后程序卡住了
- php - WooCommerce 根据其他变体库存的数量更新产品变体库存状态
- r - 当原始函数没有返回“ggplot”对象时,获取 ggplot 对象的数据
- java - 在运行时在 Java 中查找具有相同全名的类
- microsoft-teams - 从消息操作的 HTML contentType 中获取卡片信息
- sass - 没有名为 flexdisplay 的 mixin
- angular - 如何使用 ngx-bootstrap datepicker 以角度禁用今天和未来的日期?
- maven - 如何解决跳过 maven 单元测试的构建问题?
- java - 在java中将JSON数组从文件保存到JSONArray(对象)中