Function Prototype in C Language
As we all know, before using a variable we need to declare it. Similarly, before using a function we need to declare the function. This declaration of the function is called as function prototyping.
Consider the below program.
float fnGetAverage(int, int); void main() { int x,y; float z; printf(“\nEnter the values for x and y”); scanf(“%d %d”, &x, &y); z = fnGetAverage(x, y); //function call printf(“\nThe average is %d”, z); } float fnGetAverage(int a, int b) { //function definition float c; c = (a+b)/2; //calculating average return c; //returning the value }
There is one statement before the main() function.
The statement is: float fnGetAverage(int, int);
This statement is called function prototype. By doing this we are telling the compiler that we will use the function having following features:
- The function name would be fnGetAverage
- The function will return float value
- The function will contain two int arguments
If we do not wish to use function prototyping then we need to define the function before calling it
This can be done as follows:
float fnGetAverage(int a, int b) { //function definition float c; c = (a+b)/2; //calculating average return c; //returning the value } void main() { int x,y; float z; printf(“\nEnter the values for x and y”); scanf(“%d %d”, &x, &y); z = fnGetAverage(x, y); //function call printf(“\nThe average is %d”, z); }
Nice post….didnt know I could avoid prototyping by writing the function before main ().
What would be the reasons for wanting to avoid prototyping?
no specific reason, just that we want to avoid to hassle of writing a prototype AND definition, when u could just write the prototype.
printf(
Yes @anonymous dated dec 17th. It was an error on the previous lesson as well.
NICE WORK
nice