Introduction to Functions in C


When we write a program to solve a larger problem, we divide that larger problem into smaller subproblems and are solved individually to make the program easier. In C, this concept is implemented using functions. Functions are used to divide a larger program into smaller subprograms such that program becomes easy to understand and easy to implement. A function is defined as follows...

Function is a subpart of program used to perform specific task and is executed individually.

Every C program must contain atleast one function called main(). However a program may also contain other functions.

Every function in C has the following...

  • Function Declaration (Function Prototype)
  • Function Definition
  • Function Call

Function Declaration

The function declaration tells the compiler about function name, datatype of the return value and parameters. The function declaration is also called as function prototype. The function declaration is performed before main function or inside main function or inside any other function.

Function declaration syntax -

returnType functionName(parametersList);

In the above syntax, returnType specifies the datatype of the value which is sent as a return value from the function definiton. The functionName is a user defined name used to identify the function uniquely in the program. The parametersList is the data values that are sent to the function definition.

Function Definition

The function definition provides the actual code of that function. The function definition is also known as body of the function. The actual task of the function is implemented in the function definition. That means the actual instructions to be performed by a function are written in function definition. The actual instructions of a function are written inside the braces "{ }". The function definition is performed before main function or after main function.

Function definition syntax -

returnType functionName(parametersList)
{

Actual code...

}

Function Call

The function call tells the compiler when to execute the function definition. When a function call is executed, the execution control jumps to the function definition where the actual code gets executed and returns to the same functions call once the execution completes. The function call is performed inside main function or inside any other function or inside the function itself.

Function call syntax -

functionName(parameters);

Advantages of Functions

  • Using funcions we can implement modular programming.
  • Functions makes the program more readable and understandable.
  • Using functions the program implementation becomes easy.
  • Once a function is created it can be used many times (code re-usability).
  • Using functions larger program can be divided into smaller modules.