8

我遇到一个处理菜单的程序的一些例子..

正如我所理解的那样,他在 main 函数之前声明了所有函数,然后在 main 中也提到了一个 void 函数的函数:

char get_choice(void);
char get_first(void);
int get_int(void);
void count(void);
int main(void)
{
    int choice;
    void count(void);
    while ( (choice = get_choice()) != 'q')
    {
        switch (choice)
        {
            case 'a' : printf("Buy low, sell high.\n");
                break;
            case 'b' : putchar('\a'); /* ANSI */
                break;
            case 'c' : count();
                break;
            default : printf("Program error!\n");
                break;
        }
    }
    printf("Bye.\n");

...(功能实现)

你能告诉我这是为什么吗?tnx

4

4 回答 4

6

完全没有理由,这只是原型的无意义重复。

于 2013-01-31T16:42:26.153 回答
4

These are just declaration of the functions not definitions.Not too sure why count function is declared twice though.The declaration is just saying to the compiler that there is something there with this name.Perhaps the programmer forgot to define the method?

A declaration provides basic attributes of a symbol: its type and its name. A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored.

eg declaration looks like this:

void count(void);

eg definition looks like this:

void count(void){

......

}
于 2013-01-31T16:47:35.520 回答
3

没关系 - 任何对您的程序有意义的地方。显然,如果它在 main 内部,那么在实际函数实现之前没有其他函数会“知道”函数原型是什么,这会产生影响。

我个人倾向于在调用该函数之前实现它,这样可以避免将原型放在哪里的问题[除非它放在头文件中,在这种情况下往往会解决问题]。

于 2013-01-31T16:42:59.830 回答
1

你能告诉我这是为什么吗?tnx

除了这是一个简单的错误之外,没有其他原因;作者只是错过了多余的声明。只要两个声明相同,就不是问题(尽管它很难看,应该清理一下)。

FWIW,这就是为什么我总是在函数在同一个文件中使用之前定义它们。定义算作声明,所以只需要担心一个原型。

于 2013-01-31T21:48:47.733 回答