#include <stdio.h> #include <Stdlib.h> int ff(); int main() { clrscr(); ff(); ff(2); ff(2,3,4); return 3; } int ff(int i,int j,int k) { printf(" \n Hello world %d %d %d\n",i,j,k); return 3; }
We can see that the first two calls to the function result in garbage values being printed for the unspecified parameters (i , j, and k in the first call and j and k in the second call). The last call prints the correct values as all the parameters have been specified. For the functions developed in the last section, the following are valid prototype declarations.
void sayhello(void); int n_abs(int n); or int n_abs(int); float reciproc(float x); or float reciproc(float); char get_yesno(void);
Notice that every prototype declaration ends with a semi-colon. The easiest way to put a declaration is to simply copy the header from the function definition, paste it, and add a terminating semi-colon. Prototype declarations are optional in C but they are compulsory in C++. Since, it is a reasonable assumption that every C programmer is a future C++ programmer , you should develop the habit of declaring prototypes for every function! The C program, demonstrates the three aspects of a user defined function – the function prototype declaration, the function definition, and function calls.
/*creating and using a user-defined function*/
#include <Stdio.h> /* function prototype declaration*/ float reciproc(float x); int main() { float x=5.67, y; clrscr(); y = reciproc(x); /*a call to the function recipro*/ printf("%g %g",y, reciproc(y)); return 0; /* another function call*/ } float reciproc(float x) { float y; y = 1.0/x; return y; }
Another advantage of using function prototype declarations is that the functions can be defined in any order in the source file. Otherwise, some compilers place a restriction that a function should be used (i.e., a function call statement is placed) only after it has been defined. Once you have declared the prototypes of all functions, this restriction does not apply and you are free to reorder your functions in any order. As a matter of style, main is usually the last or the first function in a program depending on personal stylistic preferences. Many programming books show main as the last function in a source file but I prefer to place main as the first function in a program as I feel that it improves the readability of the program.