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.

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.

Declaring a Function in C
Declaring a Function in C

The above example doesn’t have any problem while executing it on the compiler.

The image below shows the successful compilation of the program.

Declaring a Function in C Below Main
Declaring a Function in C Below Main

Now we will change the return type of the function to float, as shown in the image below.

Declaring a Function in C with float return type
Declaring a Function in C with float return type

Now we will compile the program.

The image below shows the errors after compilation.

Declaring a Function in C with float return type error message
Declaring a Function in C with float return type error message

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.

Declaring a Function in C above main function
Declaring a Function in C above main function

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.

Declaring a Function in C
Declaring a Function in C

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.