Wednesday, January 24, 2018

Structure of a Function in C programming

At that point we should have a good idea on C programming so it is time to move on a topic like Function. What is function? It is little bit difficult to explain in a sentence. We know what is loop and what it does, right? We used loop to execute any block of code several times but what if I want to repeat any block of code at any time/part of our program! Exactly, we can do this using function.


Function is a self contained block of statements which we can use whenever we want. Every Program has at least one function in C programming called ‘main()’.


Structure of a function
return_type  function_name ( parameter_list )
{
     // Function body
}

return_type : return_type is the date type which any function returns in C. Function in C must have a return type.

Functions may or may not return any value. If it does not returns any value then the return_type will be void. void function indicates it returns nothing.

function_name : function_name is simply the name of the function.

parameter_list : Parameters are like placeholder. Any function may have zero or more parameters. Any types of parameters can be used in a function. If there are more than one parameters then every parameter will be separated by a comma.

Types of Function in C
  • Standard Library Functions ( ex. scanf(), printf(), etc )
  • User Defined Functions

Look at the following example for better understanding

#include <stdio.h>

int add ( int a, int b )
{
    int result = a + b;
    return result; 
}

int main()
{
    int a, b;
    scanf("%d %d",&a, &b);
    
    int sum = add(a, b);   // calling function from main.
    printf("Summation of given two number is %d \n", sum);

    return 0;
}


Note
  • Above function has a return value of integer.
  • return keyword is used in C to return value from function.
  • To use any function in C programming, it must be called from the main function otherwise it won't work.

Advantages of using Function in C
  • We can reuse our code at anywhere in our program.
  • It makes debugging and editing more easier.
  • It makes program more readable.
  • It makes code more optimized.


Previous Topic

Next Topic



No comments:

Post a Comment