2015-02-17 127 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