#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/