Why use function prototypes?

自作多情 提交于 2019-12-21 03:37:08

问题


Why use function prototypes in C? It seems sort of redundant because we already declare the function name, argument types, and return type in the definition. Do the prototypes have to be declared before the function is defined or used for the optimizations?


回答1:


Generally speaking, you don't need to explicitly declare functions because defining them also declares them. Here are two situations where you would need to:

  1. The definition of the function is in an external module.

    For example, if the function is defined in foo.c, but you want to call it from bar.c, you will need to declare the function in bar.c or a file included by it (typically, foo.h).

  2. The definition of the function comes after a call to it.

    For example, if you have two functions that call each other, you will need to declare the second one before the definition of the first one.




回答2:


While a function definition specifies what a function does, a function prototype can be thought of as specifying its interface.

Creating library interfaces: By placing function prototypes in a header file, one can specify an interface for a library.


回答3:


With the declaration of a function the compiler can check the consistent use of parameters and return value, and can compile the code even if the function is not implemented in this module. If the function is only declared but not implemented in the respective module, this gap will be closed by the linker, not the compiler.

It's similar to declaring extern variables. If you'd define them, the memory for them would be allocated multiple times. That's why you should never define variables in h-files, but declare them there. Including the h-file would result in multiple allocations of memory.



来源:https://stackoverflow.com/questions/21670671/why-use-function-prototypes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!