× Home Introduction Structure of program Variables and keywords Constants Data Types Operators Statements Functions Storage Classes Array Structure Pointer Union Strings Header Files
☰ Topics

Functions in C

A function is a block of code that performs a specific task. C program does not execute the function directly. It is required to invoke or call that functions. When a function is called in a program then program control goes to the function body and executes the statements in the function. Function prototype tells compiler that we are going to use a function which will have given name, return type and parameters.

Types of function:

There are two types of functions as:

    Built in Functions
    User Defined Functions
  1. Built in Functions:
  2. These functions are also called as 'Library Functions'. These functions are provided by system. These functions are stored in library files. e.g.

    scanf() printf() strcpy() strcmp() strlen() strcat()

  3. User Definied Functions:
  4. The function which are created by user for program are known as 'User defined functions'.

    Functions with no argument and no return values.

    Functions with arguments and no return value.

    Functions with argumens and return value.

        

    void add(int x, int y) { int result; result = x + y; printf("sum of %d and %d is %d.\n\n",x,y,result); } void main() { add(10,15); add(55,64); add(168,325); }

Passing Parameters to a Function

There are two ways to pass parameters to a function:

Example: Pass by value

  

int main() { int a = 10; int b = 20; Printf("Before: Value of a = %d and value of b = %d\n", a, b); swap(a,b); printf("After: Value of a = %d\n", a, b); } void swap(int p1, int p2) { int t; t = p2; p2 = p1; printf("Value of a(p1) = %d and value of b(p2) = %d\n", p1, p2); } output: Here the values of a and b remain unchanged before calling swap function and after calling swap function. Before: Value of a = 10 and value of b = 20 Value of a(p1) = 20 and value of b(p2) = 10 After: Value of a = 10 and value of b = 20

Example: Pass by reference

      

int main() { int a = 10; int b = 20; Printf("Before: Value of a = %d and value of b = %d\n", a, b); swap(&a,&b); printf("After: Value of a = %d\n", a, b); } void swap(int *p1, int *p2) { int t; t = *p2; *p2 = *p1; printf("Value of a(p1) = %d and value of b(p2) = %d\n", *p1, *p2); } output: Here the values of a and b are changes after calling swap function. Before: Value of a = 10 and value of b = 20 Value of a(p1) = 20 and value of b(p2) = 10 After: Value of a = 10 and value of b = 20

Advantages

Recursion (Recursive Function)

A recursive function is one which calls itself.

Features:

Advantages:

Disadvantages:

Next Topic ➤