c - 函数声明如何工作?

标签 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 中的函数声明是否总是针对每个函数?

最佳答案

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

#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 结束后超出范围的意义上说,你既对又错。在链接器会混淆东西的意义上是错误的,链接器决定什么函数调用调用什么,可以找到 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: error: implicit declaration of function ‘foo’ [-Werror=implicit-function-declaration]

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

关于c - 函数声明如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21463123/

相关文章:

c - 为什么 ioctl 调用没有传递给 sys_ioctl?

函数指针可以用来运行 "data"吗?

function - 对 R 中的每一行执行 if 语句

javascript - 这是一个纯函数吗?

php - 使用变量定义 PHP 函数

c++ - 函数 try block 是否允许我们解决异常?

可以将地址运算符应用于非整数类型的二维数组和 C 中结构的非整数字段吗?

C#include sth 依赖混淆

c - 这个自定义 toupper() 函数如何工作?

javascript - 是否可以绑定(bind)一个javascript函数,使其本地上下文与 'this'相同?