为什么函数声明需要在这? [英] Why Function declaration needed in this?

查看:277
本文介绍了为什么函数声明需要在这?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code:

#include <stdio.h>
int navin();   //function declaration
int main()
{
    int i = navin(); //function call
}
int navin() //function definition
{
     printf("Hello");   
}

输出:
您好

问:

如果我们去掉函数声明行 INT纳文();从上面的code ,它打印相同。那么,为什么使用它?

If we remove the function declaration line int navin(); from the above code, it prints the same. Then why it is used?

推荐答案

这里的函数声明称为向前声明。这是用来当函数被调用[使用]的之前的它被定义。

The function declaration here is called the forward declaration. This is used if the function has been called [used] before it is defined.

在您的code,看到的,当纳文()被称为内的main(),在这一点上,该函数还没有定义。通过使用前置声明,你告诉编译器,

In your code, see, when navin() is called inside main(), at that point, the function is not yet defined. By using the forward declaration, you're telling compiler,

这是函数签名。这个函数定义为present后来在code,继续编辑。

"This is the function signature. This function definition is present later in the code, continue the compilation."

如果没有这个前置声明,大多数 C 编译器会告诉你一个警告[称为隐式声明]他们无法找到函数纳文(),所以,编译器的假设的函数原型为

Without this forward declaration, most of the c compilers will show you a warning [termed as implicit declaration] that they are not able to find the function navin(), so, the compiler will assume the function prototype as


  • 任意数量的输入参数

  • 返回类型为整数。

在大多数情况下,这结束了在灾难。

In most of the cases, this ends up in a disaster.

您可以在更多信息这的相关的问题。

You can find more information in this related question.

深刻用法:头文件

请注意:

在旧的 C 标准 C89 ,这应该是只是一个警告,但较新的版本, C99 C11 定义此[缺少向前声明]是一个错误。然而,在默认情况下 GCC [C在Linux上编译]不执行这些标准。如果你告诉 GCC 明确遵循 C99 及更高版本,它会产生的正确的错误消息。

In older c standards, c89, this was supposed to be only an warning, but the newer versions, c99 and c11 defines this [missing forward declaration] to be an error. However, by default gcc [c complier on linux] doesn't implement these standards. If you tell gcc explicitly to follow c99 and higher, it'll produce the correct error message.

这篇关于为什么函数声明需要在这?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆