2015-02-17 130 views
-5

這是一個簡單的菜單。提示用戶選擇介於0和3之間的數字。運行時,如果在提示符下輸入1,則會輸出「Hello2」,這是正確的。然而,在第9行,當它應該返回值1(數字輸入存儲爲「類型」變量,它返回0.它將返回0爲任何值輸入。有人可以告訴我,我哪裏錯了在這裏?謝謝爲什麼這個開關盒總是返回0?

#include <stdio.h> 

int type; 

int main(int argc) 
{ 
    int a = 7; 
    getInput(); 
    printf("You selected: %d\n", type); 
}  

int getInput(type) 
{ 
    printf("\nPlease select an option:\n1)Create a record\n2)Display records\n 
      3)Update records\n4)Exit\n\n;"); 
    scanf("%d", &type); 

    switch(type) 
    { 
     case 0: 
     printf("Hello\n"); 
     break; 
     case 1: 
     printf("Hello2\n"); 
     break; 
     case 2: 
     printf("Case3\n"); 
     break; 
     case 3: 
     printf("Exit\n"); 
     break; 
     default: 
     printf("\nERROR! Please select a valid number\n");  
    }  
} 
+0

爲避免此錯誤,請使用函數原型。你的代碼在C99中是非法的(在使用它們之前至少要聲明哪些函數)。 – 2015-02-17 22:19:28

+0

不要忽略'scanf()'的返回值。 – 2015-02-17 22:23:10

+0

打開編譯器警告並注意它們。 – 5gon12eder 2015-02-17 22:23:22

回答

1

type要修改是在getInput一個局部變量。如果要修改全局的,刪除功能參數:

int getInput(void) { .... } 

還要確保從返回的東西getInput或退貨類型void

void getInput(void) { .... } 

一個好的解決方法是從函數中刪除全局變量並返回type。修復該問題和其他問題:

int getInput(void) 
{ 
    int type = 0; 
    /* 
    as before 
    */ 

    return type; 
} 

#include <stdio.h> 

int main(void) 
{ 
    int a = getInput(); 
    printf("You selected: %d\n", a); 
} 

注意函數簽名int getType(type)在C89的隱含參數類型int,但是從C99開始失效。

3

首先,你的代碼在現代C語言中是不可編譯的。函數getType未在調用點聲明。 C語言不允許你調用未聲明的函數。

而且這個

int getInput(type) 
{ 
    ... 

是一個老K & R風格定義,它依賴於 「隱int」 的規則。現代C語言不再有「隱含的int」規則,這就是爲什麼你的代碼無效。其次,如果您的編譯器接受該調用和R 012樣式定義,則它將其接受爲C89/90代碼,參數類型默認爲int。這個本地參數int type就是你正在使用的。它與全球變量type沒有任何關係,永遠保持0

第三,您的代碼在許多其他方面被打破。您使用參數定義了函數getInput,但是不帶任何參數地調用它。這會導致未定義的行爲。第四,儘管C中沒有立即出現錯誤,但是您的getInput被聲明爲返回int,但您永遠不會從中返回任何內容。

+1

另外'int main(int argc)'不是C89中'main'的有效聲明。 – ouah 2015-02-17 22:31:24