2017-06-29 123 views
0

這是我的某個程序的代碼。但是,什麼是殺害我的是,在功能getTotalX,在內部如果塊的for循環,當標誌break語句後更新爲0事實上,它得到更新回到1。這是爲什麼發生?我認爲break語句可以幫助我擺脫for循環,並直接轉到下一個語句。break語句後分配的值會發生什麼?

#include <stdio.h> 


int getTotalX(int a_size, int* a, int b_size, int* b){ 
    int min = a[a_size-1]; 
    int max = b[0]; 
    int count = 0; 

    for(int i = min; i <= max; i++){ 
     int flag1 = 1, flag2 = 1; 
     for(int j = 0; j < a_size; j++){ 
      printf("In array a,value of %d mod %d is %d \n",i,a[j],i%a[j]); 
      if((i % a[j]) != 0){ 
       int flag1 = 0; 
       printf("flag1 set to 0. Check flag1 = %d\n",flag1); 
       break; 
      } 
     } 
     printf("Checkpoint2, value of flag1 = %d\n",flag1); 
     if(flag1 != 0){ 
      for(int k =0; k < b_size; k++){ 
       printf("In array b,value of %d mod %d is %d \n",b[k],i,b[k]%i); 
       if((b[k] % i) != 0){ 
        int flag2 = 0; 
        printf("flag2 set to 0. Check flag2 = %d\n",flag2); 
        break; 
       } 
      } 
     } 
     printf("Checkpoint3, value of flag2 = %d\n",flag2); 


     if((flag1 == 1) && (flag2 == 1)){ 
      printf("Value of flag1 = %d and flag2 = %d\n",flag1,flag2); 
      printf("%d \n ",i); 
      count++; 
     } 
    } 
    return(count); 

} 

int main() { 
    int n; 
    int m; 
    scanf("%d %d", &n, &m); 
    int *a = malloc(sizeof(int) * n); 
    for(int a_i = 0; a_i < n; a_i++){ 
     scanf("%d",&a[a_i]); 
    } 
    int *b = malloc(sizeof(int) * m); 
    for(int b_i = 0; b_i < m; b_i++){ 
     scanf("%d",&b[b_i]); 
    } 
    int total = getTotalX(n, a, m, b); 
    printf("%d\n", total); 
    return 0; 
} 

所有的打印聲明都是爲了幫助我弄清楚我哪裏出錯了。我可以改變邏輯來使其工作,但請幫助我理解爲什麼會發生這種情況?

回答

2

在內部for內的if塊聲明的int flag1從外for的塊宣佈int flag1一個不同的變量。只要宣佈第二個int flag1前一個是被遮蔽的,並且直到發生陰影聲明的塊的末尾才能按名稱訪問。

for(int i = min; i <= max; i++){ 
    int flag1 = 1, flag2 = 1;     // This is the outer flag1 
    for(int j = 0; j < a_size; j++){ 
     printf("In array a,value of %d mod %d is %d \n",i,a[j],i%a[j]); 
     if((i % a[j]) != 0){ 
      int flag1 = 0;     // This is the inner flag1 
     // The inner flag1 and the outer flag1 are different variables. 
     // The inner flag1 is set to zero, the outer flag1 is not changed. 
      printf("flag1 set to 0. Check flag1 = %d\n",flag1); 
      break; 
     } 
     // The brace ending the block ends the scope of the inner flag1. 
     // From now on the name flag1 refers to the outer flag1. 
    } 
+3

的好處['-Wshadow'](https://stackoverflow.com/questions/25151524/get-warning-when-a-variable-is-shadowed)不能被低估。 – dhke

+0

哦,太棒了!哇。 – momo