Declaring Functions in C
For Complete YouTube Video: Click Here
In this class, we will try to understand Declaring Functions in C.
We have already discussed the basics of functions and Defining the Calling and return statement of a function.
Table of Contents
Need to Declare a Function
The image below is an example that we have seen in our Defining the Calling and return statement of a function class.
The above example doesn’t have any problem while executing it on the compiler.
The image below shows the successful compilation of the program.
Now we will change the return type of the function to float, as shown in the image below.
Now we will compile the program.
The image below shows the errors after compilation.
The error states conflicting types for sum.
Why we got this error?
As we have already discussed, that c compiler will compile the programs sequentially from top to bottom.
In that process, the compiler has compiled the function call first.
As the definition of the function call appears below the function call, the compiler will inherently assume the return type to be of int type.
When the compiler comes to the definition of the function, it is defined as a float type.
That is why the error is stating conflicting types for sum.
Now we will change the definition of the function above the ‘main’ function as shown in the image below.
In such cases, there will not be any compilation errors.
The definition of the functions looks very tedious to write the program.
To avoid the definition of the function on the top of the ‘main()’ function c compiler provides an option to declare a function.
Declaring a Function
The image below shows the program with function declarations.
In the function declaration return types, the name of the function and the parameter types and names are to be mentioned.
The names of the parameters are not mandatory.
We can mention the types of parameters as shown in the image below.
With this kind of declaration, we can avoid conflicting types.