函数声明如何工作?

时间:2014-01-30 17:17:09

标签: c function

    #include <stdio.h>
    void bar();

    int main()

    {

        void foo();

        printf("1 ");

        foo();
        bar();

    }

    void foo()

    {

        printf("2 ");

    }
    void bar()
    {
        foo();
    }

输出:

1 2 2

函数foo()不应仅在main()中可见吗? 但事实并非如此 C中的函数声明是否始终适用于每个函数?

2 个答案:

答案 0 :(得分:3)

让我解释一下您粘贴的原始代码:)

#include <stdio.h>
void bar(); //so, we declared bar here, thus it will be called successfully later

int main()

{

    void foo(); //we declared foo here, thus the foo two statements below also can be called

    printf("1 ");

    foo(); //this works because the void foo(); some lines above
    bar(); //this works because of bar() outside the main()

}

void foo() //here foo is defined

{

    printf("2 ");

}
void bar() //here bar is defined
{
    foo(); //this works because foo was declared previously
}

事实上,你是正确的,也是错的,因为foo()的第一个声明在主要结束后超出了范围。错误的是,链接器会混淆东西,链接器决定调用什么函数调用什么,可以在main之外找到foo,并且在main中声明的是相同的foo。

那就是说,你不应该在其他函数中声明函数......

此处还有一个更好的证明你想知道的事情:

我试图编译这个:

#include <stdio.h>
void bar();

void bar()
{
    void foo();
    foo();
}

int main()

{



    printf("1 ");

    foo(); //line 18
    bar();

}

void foo()

{

    printf("2 ");

}

它给了我这个错误:prog.c:18:9:错误:隐式声明函数'foo'[-Werror = implicit-function-declaration]

这是因为bar()里面的foo()是有效的,但main上的foo()不是,因为虽然foo()在main之前声明,但它仍然只在bar()中有效

答案 1 :(得分:1)

foo()在bar()中可见,因为它之前已经定义过。 如果在bar()之后实现foo(),则会出现编译错误

#include <stdio.h>
void bar();

int main()

{

    void foo();

    printf("1 ");

    foo();
    bar();

}


void bar()
{
    foo();
}
void foo()

{

    printf("2 ");

}

带来:

'foo': identifier not found
相关问题