首页 > 解决方案 > 关于块范围链接,没有错误,没有警告,但结果很惊讶,我不知道为什么

问题描述

#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

标签: cscope

解决方案


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 $ 

推荐阅读