c - c中函数声明的范围

标签 c function calling-convention function-declaration

我在很多地方读到,在 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

fun1fun2 在调用之前都不会声明 fun3,也不会在 ; main 中的 fun3 声明仅限于 main 主体。在 C89 及更早版本下,编译器将假定对 fun3 的调用返回 int。在第一个示例中,fun3定义返回一个int,因此代码将在 C89 编译器下编译。在第二个示例中,fun3 的定义返回 void,它与假定的 int 类型不匹配,因此代码无法编译。

在 C99 及更高版本的标准下,这两个代码段都无法编译;编译器不再为函数调用假定隐式 int 声明。 所有函数在调用之前都必须显式声明或定义。

关于c - c中函数声明的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31099758/

相关文章:

c++ - nasm/yasm 参数,与 C++ 的链接

crash - 使用 VC2010 修复 libvlc Release模式崩溃

c - C中位的右循环

c - GCC 动态链接 libc static 和其他一些库,重新访问了吗?

function - 有没有办法从函数内检索 PowerShell 函数名称?

c++ - 简单的功能大小;了解指针与指针的区别

linux - i386 和 x86-64 上的 UNIX 和 Linux 系统调用(和用户空间函数)的调用约定是什么

c - 使用函数修改结构体中字符串的内容

c - fread 不读取多行

string - Delphi 汇编函数返回长字符串