在C中调用函数而不生成函数

时间:2013-02-02 00:31:40

标签: c function visual-studio-2012

我是C的新手,到目前为止非常不同。不过我试图使用scanf和switch语句从main函数调用一个函数,但我不相信我调用的函数正在运行。

int main(void)
{
    int Example_number = 0;
    bool Continue = true;
    char ch;

    while(Continue)
    {
        printf("Which example would you like to run?\n");
        scanf("%d",&Example_number);

        switch(Example_number)
        {
        default: printf("No such program exists.\n");
                 break;
        case 1:  void Various_test();
                 break;
        }

        printf("Would you like to test another?(Y/N)\n");
        scanf("\n%c",&ch);
        if(ch == 'Y' || ch == 'y')
        {
            NULL;
        }
        else
        {
            Continue = false;
        }
    }
}

void Various_test(void)
{
    int k = 2;
    printf("\n%d",k);
}

我希望程序打印2如果1是输入,但是while循环只是重复。

感谢您对此问题的考虑。

2 个答案:

答案 0 :(得分:4)

void Various_test()是函数的前向声明。要打电话给你,你真的只想要Various_test()。您可能实际上需要前向声明(取决于您的编译选项)。在这种情况下,将void Various_test();置于main之上。

答案 1 :(得分:1)

你可以做以下两件事之一:

在main的开头添加函数声明,如下所示:

int main(void)
{
    void Various_test(void);
    ...

或者,将Various_test的函数定义移到main之前,如下所示:

void Various_test(void)
{
    int k = 2;
    printf("\n%d",k);
}

int main(void)
{
    int Example_number = 0;
    ...

您选择的任何一种方式都会起作用。正如你现在所做的那样,编译器不知道Various_test函数。无论哪种方式都告诉编译器有一个名为Various_test的函数,这就是它的样子。

还有一件事,你在switch语句中调用Various_test错误:

case 1:  void Various_test();

应该是:

case 1:  Various_test();