吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → 在 C 中声明函数之前调用函数会发生什么

在 C 中声明函数之前调用函数会发生什么

来源:网络 | 更新时间:2022-01-14 22:29:44
在 C 中,如果函数在声明之前被调用,编译器会假定函数的返回类型为 int 例如,下面的程序编译失败。
#include <stdio.h>
int main(void)
{
// Note that fun() is not declared
printf("%cn", fun());
return 0;
}

char fun()
{
return 'G';
}
如果上面代码中的函数char fun()是在 main() 和调用语句后面定义的,那么它就不会编译成功。因为编译器默认假定返回类型为“int”。并且在声明时,如果返回类型与 int 不匹配,则编译器将给出错误。 以下程序编译并运行良好,因为函数是在 main() 之前定义的。
#include <stdio.h>

int fun()
{
return 10;
}

int main(void)
{
// Note the function fun() is declared
printf("%dn", fun());
return 0;
}
参数呢?编译器对参数没有任何假设。因此,当函数应用于某些参数时,编译器将无法执行参数类型和数量的编译时检查。这可能会导致问题。例如,以下程序在 GCC 中编译得很好,并产生了垃圾值作为输出。 
#include <stdio.h>

int main (void)
{
printf("%d", sum(10, 5));
return 0;
}
int sum (int b, int c, int a)
{
return (a+b+c);
}
编译器假定输入参数也是 int 存在这种误解。如果编译器假定输入参数为 int,则上述程序将无法编译。 总是建议在使用之前声明一个函数,这样我们在程序运行时就不会看到任何意外  

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com