I'm following a guide to learn curses, and all of the C code within prototypes functions before main()
, then defines them afterward. In my C++ learnings, I had heard about function prototyping but never done it, and as far as I know it doesn't make too much of a difference on how the code is compiled. Is it a programmer's personal choice more than anything else? If so, why was it included in C at all?
The Function prototype serves the following purposes – 1) It tells the return type of the data that the function will return. 2) It tells the number of arguments passed to the function. 3) It tells the data types of each of the passed arguments.
Importance of Function Prototype It tells the return type of the data that the returning of the function will happen. Furthermore, it tells the number of arguments that are passed to the function. It tells each passed arguments data types.
It is not needed, but not using prototypes is bad practice. The compiler can use prototypes to make sure you're calling the function appropriately (using the right number and type of parameters).
A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body. A function prototype gives information to the compiler that the function may later be used in the program.
In C prototyping is needed so that your program knows that you have a function called x()
when you have not gotten to defining it, that way y()
knows that there is and exists a x()
. C does top down compilation, so it needs to be defined before hand is the short answer.
x();
y();
main(){
}
y(){
x();
}
x(){
...
more code ...
maybe even y();
}
Function prototyping originally wasn't included in C. When you called a function, the compiler just took your word for it that it would exist and took the type of arguments you provided. If you got the argument order, number, or type wrong, too bad – your code would fail, possibly in mysterious ways, at runtime.
Later versions of C added function prototyping in order to address these problems. Your arguments are implicitly converted to the declared types under some circumstances or flagged as incompatible with the prototype, and the compiler could flag as an error the wrong order and number of types. This had the side effect of enabling varargs functions and the special argument handling they require.
Note that, in C (and unlike in C++), a function declared foo_t func()
is not the same as a function declared as foo_t func(void)
. The latter is prototyped to have no arguments. The former declares a function without a prototype.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With