必须声明函数原型用C? [英] Must declare function prototype in C?

查看:199
本文介绍了必须声明函数原型用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点新的C(我有事先的Java,C#和一些C ++经验)。在C,是有必要声明函数的原型,也可以在code编译没有它?它是良好的编程习惯这样做呢?或者它只是取决于编译器? (我运行Ubuntu 9.10和使用GNU C编译器,或GCC,在code :: Blocks的IDE下)

I am kind of new to C (I have prior Java, C#, and some C++ experience). In C, is it necessary to declare a function prototype or can the code compile without it? Is it good programming practice to do so? Or does it just depend on the compiler? (I am running Ubuntu 9.10 and using the GNU C Compiler, or gcc, under the Code::Blocks IDE)

推荐答案

在ANSI C(即C89 C90或),你不必声明函数的原型;但是,它是使用它们的最佳做法。唯一的原因,标准,您可以不使用它们是非常旧code的向后兼容性。

In ANSI C (meaning C89 or C90), you do not have to declare a function prototype; however, it is a best practice to use them. The only reason the standard allows you to not use them is for backward compatibility with very old code.

如果你没有一个原型,你调用一个函数,编译器会推断传递给函数的参数的原型。如果在同一编译单元声明功能后,即使你的函数的签名是由编译器猜到了不同得到一个编译错误。

If you do not have a prototype, and you call a function, the compiler will infer a prototype from the parameters you pass to the function. If you declare the function later in the same compilation unit, you'll get a compile error if the function's signature is different from what the compiler guessed.

更糟的是,如果函数是在另一个编译单元,有没有办法得到一个编译错误,因为没有一个原型有没有办法来检查。在这种情况下,如果编译器得到它错了,你可以,如果函数调用堆栈上推动不同类型得到了一个未定义的行为比函数需要。

Worse, if the function is in another compilation unit, there's no way to get a compilation error, since without a a prototype there's no way to check. In that case, if the compiler gets it wrong, you could get undefined behavior if the function call pushes different types on the stack than the function expects.

公约是始终在具有相同的名称,包含该函数的源文件的头文件中声明的原型。

Convention is to always declare a prototype in a header file that has the same name as the source file containing the function.

在C99或C11,C标准要求的范围函数声明中调用任何函数之前。除非你强迫他们这样做,许多编译器不执行在实践中这个限制。

In C99 or C11, standard C requires a function declaration in scope before you call any function. Many compilers do not enforce this restriction in practice unless you force them to do so.

这篇关于必须声明函数原型用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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