Function in C

Function is a group of statements that are used to perform any task. In other words, we can say that a function is a self- contained a block of programs that perform a coherent task.

Why to use function

A function is used to divide a large code into modules that help us to debug and maintain the code. We can call any function multiple times.

There are various advantages of function:

  • Code re-usability
  • Easy to debug the program
  • Code optimization.

Types of Functions

In C language, there are two types of functions that are given below:

 

  1. Library Function :

A library function is used to declare the c header file such as scanf(), printf() and many more.

  1. User-defined function

User define function is used to create own function and we can use it multiple times.

Defining a Function

We can define a function by using the following syntax:

Syntax:

The function definition consists of a function header and a function body. There are the following parts of a function.

  1. Return type: A function may return a value. If we don’t want to return a value then we have to use void.
  2. Function name: We can define the function name.
  3. Parameters: We can pass the value in function at the time of calling.
  4. Function body: Function body is the collection of statements.

Let us consider an example:

Output

Call by value and call by Reference in C

In C language, there are two ways to pass the value of data to function.

  • call by value.
  • call by reference.

 

Call by value:

We can’t change the original value at the time of passing value in the function but it can be changed for the current function only. It will not change the value of a variable inside the caller method such as main().

Let us consider an example:

Output

Call by reference:

We can change the original value while using call by reference through pass the reference (address).

Let us consider an example:

Output

Leave a Comment