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

📅  最后修改于: 2021-05-25 19:37:03             🧑  作者: Mango

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

C
#include 
int main(void)
{
    // Note that fun() is not declared
    printf("%c\n", fun());
    return 0;
}
 
char fun()
{
   return 'G';
}


C
#include 
 
char fun()
{
   return 'G';
}
 
int main(void)
{
    // Note that fun() is not declared
    printf("%c\n", fun());
    return 0;
}


C
#include 
 
int fun()
{
   return 10;
}
 
int main(void)
{
    printf("%d\n", fun());
    return 0;
}


C
#include 
 
int main (void)
{
    printf("%d", sum(10, 5));
    return 0;
}
int sum (int b, int c, int a)
{
    return (a+b+c);
}


如果以上代码中的char fun()函数在main()之前定义,则它将编译并完美运行。
例如,以下程序将正常运行。

C

#include 
 
char fun()
{
   return 'G';
}
 
int main(void)
{
    // Note that fun() is not declared
    printf("%c\n", fun());
    return 0;
}

下面的程序可以编译并正常运行,因为函数是在main()之前定义的。

C

#include 
 
int fun()
{
   return 10;
}
 
int main(void)
{
    printf("%d\n", fun());
    return 0;
}

参数呢?编译器不假设参数。因此,当函数应用于某些参数时,编译器将无法对参数类型和参数进行编译时检查。这可能会导致问题。例如,以下程序在GCC中编译良好,并产生了垃圾值作为输出。

C

#include 
 
int main (void)
{
    printf("%d", sum(10, 5));
    return 0;
}
int sum (int b, int c, int a)
{
    return (a+b+c);
}
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。