Basically there are three advanced topics of functions
1. Function declaration and prototypes
2. Call by value and call by reference
3. Recursion
Today I will tell you about very first topic “Function declaration and prototypes”. I have already covered the half of this topic in my earlier tutorials but I will give you an overview of that again.
Function Declaration and Prototypes
By default any C function will return an integer value to its calling function. Even if we don’t specify any prototype for the function then it is considered that it will only return integer value. To make some change in the return value we have to declare its prototype first. Lets understand with one simple example.
#include<stdio.h> squareval(float); void main() { float x, y; printf("Enter one value to obtain square n"); scanf("%f",&x); y=squareval(x); printf("Answer is %f", y); } squareval(float a) { float b; b=a*a; return(b); }
Output
I have executed above program with two values. At first I have entered 2 and it gave me correct answer 4 for it. But in the next run when I entered 1.5, it gave me wrong result by replying 2 as an answer.
Can you tell reason why it is giving wrong results for float value?
As I said earlier that by default a function always return an integer value. In our program we have not given any return type for the function squareval(). So it is returning an integer value to the main() function.
To rectify this we have to specify the return type as float in the prototype of the squareval() function. Correct version of above program is given below.
#include<stdio.h> float squareval(float); void main() { float x, y; printf("Enter one value to obtain square n"); scanf("%f",&x); y=squareval(x); printf("Answer is %f", y); } float squareval(float a) { float b; b=a*a; return(b); }
Output
Checkout now its giving correct results for float values too. Above the main() function I have declared the function squareval() with return type float. After that while defining the sqaureval() function I have again written the return type as float.
So by giving the prototype of the function we can return values as per our desired data type.
We can also declare function prototype with user defined data types like structure. We will learn it in our upcoming tutorials.