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 the program becomes easy to understand and easy to implement.

A function is a block of code that performs a particular task.

There are many situations where we might need to write same line of code for more than once in a program. This may lead to unnecessary repetition of code, bugs and even becomes boring for the programmer. So, C language provides an approach in which you can declare and define a group of statements once in the form of a function and it can be called and used whenever required.

These functions defined by the user are also know as User-defined Functions.

Function Aspects

There are three aspects of a C function.

  • Function declaration A function must be declared globally in a c program to tell the compiler about the function name, function parameters, and return type.

        Syntax 

returntype functionName(parameter lists);

  • 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 the main function or any other function or inside the function itself.

        Syntax 

functionName(parameter);

  • Function definition It contains the actual statements which are to be executed. It is the most important aspect to which the control comes when the function is called. Here, we must notice that only one value can be returned from the function.

         Syntax 

returntype functionName(parameter lists)

{

                    actual code;

 

Advantage of functions in C

There are the following advantages of C functions.

  • By using functions, we can avoid rewriting same logic/code again and again in a program.
  • We can call C functions any number of times in a program and from any place in a program.
  • We can track a large C program easily when it is divided into multiple functions.
  • Re-usability is the main achievement of C functions.
  • However, Function calling is always a overhead in a C program.
 
 
 
 



No comments:

Post a Comment