我在很多地方读到,在 main() 中声明的函数不能在 main 之外调用。但在下面的程序中, fun3() 在 main() 内部声明,并在其他函数中在 main() 外部调用,并且它可以工作,给出输出 64。这里的链接 http://code.geeksforgeeks.org/7EZZxQ但是,如果我将 fun3() 返回类型 int 更改为 void ,则无法编译,这种行为的原因是什么?
#include <stdio.h>
#include <stdlib.h>
int main()
{
void fun1(int);
void fun2(int);
int fun3(int);
int num = 5;
fun1(num);
fun2(num);
}
void fun1(int no)
{
no++;
fun3(no);
}
void fun2(int no)
{
no--;
fun3(no);
}
int fun3(int n)
{
printf("%d",n);
}
更改 fun3() 的声明时编译失败。
#include <stdio.h>
#include <stdlib.h>
int main()
{
void fun1(int);
void fun2(int);
void fun3(int); //fun3 return type changed to void error in compilation
int num = 5;
fun1(num);
fun2(num);
}
void fun1(int no)
{
no++;
fun3(no);
}
void fun2(int no)
{
no--;
fun3(no);
}
void fun3(int n) //fun3 return type changed to void error in compilation
{
printf("%d",n);
}
最佳答案
在 C99 标准之前,如果编译器在同一作用域中看到没有函数声明的函数调用,则假定该函数返回 int
。
fun1
和 fun2
在调用之前都不会声明 fun3
,也不会在 主
; main
中的 fun3
声明仅限于 main
主体。在 C89 及更早版本下,编译器将假定对 fun3
的调用返回 int
。在第一个示例中,fun3
的定义返回一个int
,因此代码将在 C89 编译器下编译。在第二个示例中,fun3
的定义返回 void
,它与假定的 int
类型不匹配,因此代码无法编译。
在 C99 及更高版本的标准下,这两个代码段都无法编译;编译器不再为函数调用假定隐式 int
声明。 所有函数在调用之前都必须显式声明或定义。
关于c - c中函数声明的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31099758/