Ad

About Block Scope Chaining, No Error, No Warning, But The Result Is Surprised And I Can Not Figure Out Why

- 1 answer

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

output:

inner: 65532
outer: 22

The output is surprised, I can not figure out why.

edit: compile method: gcc test.c

Ad

Answer

int count = count * 2;

in count * 2count 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 :

[email protected]:/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;
         ^~~~~
[email protected]:/tmp $ 
Ad
source: stackoverflow.com
Ad