术语:前向声明与函数原型
对我来说,使用 C 编程语言时这些术语本质上是同义词。在实践中,我可能更喜欢文件内原型的“前向声明”,而不是通过头文件包含的原型的“函数原型”。但当你考虑预处理后会发生什么时,即使这也是人为的区别。也许我错过了一些东西。
对于何时使用一个术语与另一个术语是否存在共识?
To me these terms are essentially synonymous when using the C programming language. In practice I might prefer "forward declaration" for in-file prototypes versus "function prototype" for prototypes included via a header file. But even that is an artificial distinction when you consider what happens after preprocessing. Perhaps I'm missing something.
Is there a consensus for when to use one term versus the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
术语“原型”是指特定的声明语法;具体来说,函数参数的数量和类型出现在声明中。给定一个函数定义,
您可以有以下任何声明:
The term "prototype" refers to a specific declaration syntax; specifically, that the number and types of parameters to the function appear in the declaration. Given a function definition of
you can have any of the following declarations:
IMO 这些并不是真正的同义词。
对我来说,“函数原型”指的是函数名称及其参数和返回的类型。它不仅适用于您所谓的“前向声明”。所有函数都有一个原型。
我们更经常区分函数声明及其相应的定义。
IMO those are not really synonyms.
To me "function prototype" refer to the function name and its parameters' and return's types. It does not only apply to what you call "forward declaration". All functions have a prototype.
We more often make a difference between a function declaration and its corresponding definition.
我使用术语“前向声明”来表示以下带有定义的 struct 声明。
为了与 1989 年之前的 (K&R) C 兼容,函数声明不必是完整的原型。
I use the term forward declaration for the following kind of
struct
declaration with a definition.A function declaration need not be a full prototype, for compatibility with pre-1989 (K&R) C.
我所知道的 C 语言中唯一的概念是声明和定义之间的区别。原型是一个声明,可以在任何地方、任何时间发生,而定义是给定对象的实际实现。根据这个概念,没有所谓的前向声明,只有声明的顺序。
The only concept in C I'm aware of is the distinction between declaration and definition. A prototype is a declaration and can happen anywhere, anytime and the definition which is the actual implementation od the given object. by that concept, there is no thing called forward declaration, ther's only an order of declaration.
我不知道是否达成共识,但我认为最简洁的方法是:
我不喜欢将声明放在文件中,因为在 C 中可能会出现冲突的声明而不会出现错误,这可能会导致段错误,例如: if ac has
和 bc has
你不会收到警告或错误,并且从 bc 调用 foo() 不会将所有参数放在堆栈上应有的位置,这意味着 foo() 只会从堆栈中抓取一些内容并将其视为字符串三,可能会导致段错误。所以对我来说,声明位于头文件中,定义位于源文件中。
I don't know if there is a consensus, but I think the cleanest way to do it would be:
I don't like to place declarations in files because you can have conflicting declarations without errors in C, which can cause segfaults, for example: if a.c has
and b.c has
you will not get warnings nor errors, and calls made to foo() from b.c will not place all the parameters on the stack where they should be, meaning foo() will just grab something from the stack and treat it as str_three, possibly leading to a segfault. So for me, declarations go to header files and definitions go to source files.