c - 一次声明多个函数如何工作?

标签 c function

#include <stdio.h>

int main()
{
    void foo(), f();
    f();
}

void foo()
{
    printf("2 ");
}

void f()
{
    printf("1 ");
    foo();
}

输出:
1 2

这里的声明是如何工作的? 如果我在 foo() 之前定义 F(),我就会出错。

错了!

#include <stdio.h>

int main()
{
    void foo(), f();
    f();
}  

void f()
{
    printf("1 ");
    foo();
}

void foo()
{
    printf("2 ");
}

错误

> main.c: In function 'f': main.c:21:13: error: incompatible implicit
> declaration of function 'foo'
>              foo();
>              ^ main.c:7:18: note: previous implicit declaration of 'foo' was here
>              void foo(), f();

              ^

为什么会这样?

最佳答案

这是一个范围问题。在第一个示例中,foof 是 main 已知的,因为您声明了它们。 f() 知道 foo 因为它是在它之前声明的。

在你的第二个例子中,ffoo 的声明是局部于 main 的,f() 不知道 foo 因为它没有在它之前声明。

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

相关文章:

C 字符串类型定义

c++ - 为什么下面的代码会进入无限循环?

C - realloc 不反射(reflect)回 main

c - 错误: Conflicting types for 'pow' in C

javascript - 调用函数——什么时候可以省略引用对象?

c - 如何创建外部结构并定义其 typedef

c - 如何在 OS X 上运行 .mm 文件?

c++ - 使用 Clang 和 WebAssembly 导入外部符号

arrays - 如何在类之外使用函数

javascript - 多个 div 创建、jquery/javascript、性能/最佳实践