The book's I'm using to learn C explains something called "prototypes" which I couldn't understand properly. In the book, the following sample code explains these "prototypes". What does this mean here? What are the "prototypes"?
//* two_func.c -- a program using two functions in one file */
#include <stdio.h>
void butler(void);
int main(void)
{
printf("I will summon the butler function.\n");
butler();
printf("Yes! bring me some tea and writable DVD's.\n");
getchar();
return 0;
}
void butler(void) /*start of function definition*/
{
printf("You rang,sir.\n");
}
Please explain in simple terms.
Function prototypes (also called "forward declarations") declare functions without providing the "body" right away. You write prototypes in addition to the functions themselves in order to tell the compiler about the function that you define elsewhere:
Your prototype void butler(void); does all of the following things:
butler exists,butler takes no parameters, andbutler does not return anything.Prototypes are useful because they help you hide implementation details of the function. You put your prototypes in a header file of your library, and place the implementation in a C file. This lets the code that depends on your library to be compiled separately from your code - a very important thing.
This is the prototype:
void butler(void);
Basically it defines butler as a function that takes no parameters and has no return value. It allows the compiler to continue onwards, even though the butler function has not yet really been defined. Note that the prototype doesn't contain any actual code. It simply defines what the butler function looks like from the outside. The actual code can come later in the file.
If your code had been
#include <stdio.h>
int main(void) {
butler(); // note this line
}
void butler() { return; }
The compiler would have stopped at the note this line section, complaining that butler() doesn't exist. It will not scan the whole file first for functions, it'll simply stop at the first undefined function call it encounters.
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