当前位置:网站首页>在 C 中声明函数之前调用函数会发生什么?

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

2022-07-01 03:18:00 三贝勒文子

在 C 中,如果函数在声明之前被调用,编译器会假定函数的返回类型为 int
例如,下面的程序编译失败。

#include <stdio.h>
int main(void)
{
    // Note that fun() is not declared
    printf("%c\n", fun());
    return 0;
}

char fun()
{
   return 'G';
}

代码编译结果:​​​​​​​

prog.c:在函数'main'中:
prog.c:5:17:警告:函数“fun”的隐式声明 [-Wimplicit-function-declaration]
  printf("%c\n", fun());
                 ^
prog.c:在顶层:
prog.c:9:6:错误:“有趣”的类型冲突
 字符乐趣()
      ^
prog.c:5:17:注意:先前隐含的“fun”声明在这里
  printf("%c\n", fun());

如果上面代码中的函数char fun()是在 main() 和调用语句后面定义的,那么它就不会编译成功。因为编译器默认假定返回类型为“int”。并且在声明时,如果返回类型与 int 不匹配,则编译器将给出错误。

以下程序编译并运行良好,因为函数是在 main() 之前定义的。​​​​​​​

#include <stdio.h>
 
int fun()
{
   return 10;
}
 
int main(void)
{
    // Note the function fun() is declared
    printf("%d\n", fun());
    return 0;
}

输出结果:

10

参数呢?编译器对参数没有任何假设。因此,当函数应用于某些参数时,编译器将无法执行参数类型和数量的编译时检查。这可能会导致问题。例如,以下程序在 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,则上述程序将无法编译。
总是建议在使用之前声明一个函数,这样我们在程序运行时就不会看到任何意外。

原网站

版权声明
本文为[三贝勒文子]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43340455/article/details/125210791