Functions

What is Function?

In general words, a function is anything that performs something.

A function is the named collection of statements that performs a specific task.

For example, printf() is a function that performs printing in C programming. Similarly in C, there are various functions to perform different tasks. Even c provides the facility to create your own functions if need.

In C, every function name is followed by a pair of parenthesis (), if the function requires some input then the input is written between the parenthesis. These inputs are called arguments or parameters. if a function requires more than one parameter then they can be written by a comma-separated list.

For example: printf("Hello"); 

In the above statement printf is the name of the function and "Hello" is the input supplied to the function, which means we want to print "Hello" using printf. 

A function can be thought of as a black box that receives input, performs something and returns the output. The output of a function is called the return value.

Types of functions

In C, functions are mainly divided into two categories

  1. Library functions / pre-defined functions
  2. User-defined functions

Library functions

In c, thousands of functions are already created to perform common tasks. These functions are defined in various files and grouped according to the purpose. For example, all input/output functions such as printf(), scanf() are defined into stdio.h file. Similarly, all mathematics operations are defined in math.h file.

Whenever we use a library function we have to include the associated header file in our program so that our program can find the reference of that library function.

User-defined functions

If you need to perform an independent task multiple times, then it is not a recommended way to write the code again and again. The best solution to create your own function once and just use that whenever required. 

These functions which are created by the user are known as user-defined functions.

Creating user defined functions

Let's understand the process of creating a user-defined function by an example. Suppose we want to create a function for calculating a function.

Now the first step to writing the logic to find the factorial of a number n. check the logic to calculate the factorial of a number as given below.

long f = 1; int i;
for(i = 1;i <= n; i++) {
  f = f * i;
}

As shown in the above code snippet, the result of factorial is calculated in variable f. As well to run the above logic we need an input of a number n.

Now we have to learn how to convert the above logic into a function and supply input and receive output.

To convert the above logic into a function first group the above statement into a single block and name that block as shown in the code snippet below...

factorial(int n) {
  long f = 1; int i;
  for(i = 1;i <= n; i++) {
    f = f * i;
  }
}

In the above code snippet, factorial() is the name of the function because every function name is followed by a pair of parentheses.

The second thing that should be noted is that if any input is required to work for function then that is received by using the parameter written inside the parenthesis. As we want to calculate factorial of a number n, so function factorial receives the number in the parameter n.

As function receives input through the parameter, similarly there is a way to return the output from the function, the way is called return value as shown in the following code snippet.

long factorial(int n) {
  long f = 1; int i;
  for(i = 1;i <= n; i++) {
    f = f * i;
  }
  return f;
}

As shown in the above code snippet, the result is calculated in a variable f and return from the function by using the return statement.

If the function returns a value then return type must be declared before the function name as shown in the above code snippet.

If a function doesn't specify a return value then by default return type is considered as int return type.

In the above code snippet, the first line of the function is called the function header and the block of statements under the function header is called the body of the function.

If we want to use the function anywhere, then only the function header is sufficient to tell how to use it, because it defines the function name, required input parameters, and the return value. so to use any function only the knowledge of function header is sufficient.

Program to calculate the factorial of a number using function,

#include<stdio.h>
//function defination
long factorial(int n) {
	long f = 1;
	int i;
	for(i = 1; i <= n; i++) {
		f = f * i;
	}
	return f;
}
int main() {
	int x;
	long f;
	
	printf("Enter any number: ");
	scanf("%d",&x);
	
	f = factorial(x); // function call
	
	printf("Factorial of %d = %ld",x,f);
	return 0;
}

Explanation

  • Every program has at least one function that is main().
  • main() is the starting point of each program.
  • As you can see to calculate the factorial of x, the main function uses the factorial() function with the input parameter x.
  • To use a function from anywhere in c program, you have to call the function. As in the above program, line-18 specifies the function call.
  • The parameter used in a function call is called the actual arguments and the parameters used in the function definition are called the formal arguments.
  • The name of the actual argument/parameter can be the same or different, even they always receives the different memory space means they are always treated as two different variables.
  • If a variable is used in a function, then it must be defined inside the function block. These types of variables are called local variables.
  • Local variables receive memory when the function is called and removed from the memory as function execution completes.

Function arguments and return values

Function arguments and return values is a way to communicate with a function.

A function argument/parameter is used to receive input in a function.

A function return value is a way to return output from the function.

A function can have multiple parameters but can have only a single return value.

If a function doesn't return a value the return type should be declared as void.

Let's understand more with the following code snippet.

int sum(int a,int b) {
	return a + b;
}

As the above code snippet receives two inputs a and b and returns the total of a and b.

There can be some other way to create the above sum function as shown in the following code snippets. Let's read carefully and then we will decide which way is the best way among all defined code snippets.

//function with no argument and no return value.
void sum() {
	int a,b;
	printf("Enter any two numbers: ");
	scanf("%d%d",&a,&b);
	
	printf("Total = %d",a + b);
}

As shown in the above code snippet, the input is received inside the function from the user as well output is printed so function doesn't return any value.

With the above code snippet, if we want to sum already define two numbers like 5 and 6. then we can't do that because function always receives input from the user.

Similarly, the above function always prints the output, but if we want to use the output in some other way then again we can't do that.

Let's try to find the solution with another code snippet.

//function with arguments and no return value.
void sum(int a, int b) {
	printf("Total = %d",a + b);
}

As shown in the above code snippet, the function can receive arguments either they are already defined or received from the user. but always prints the result.

This function is not suitable if we want to use the total in another way because it doesn't return any value.

So it is clear that the first code snippet is best because it can receive input as well as return output so output can be used in any way either for printing or use the result in any expression.

Because the first code snippet shows a two-way communication which is the best way to communicate includes receives input and return output. but sometimes two-way communication is not suitable for a purpose. see the following code snippets.

void prn() {
	printf("Hello");
}

As shown the above code snippet prints a message "Hello" so no need to receive any input and no need to return output. so this function is perfect for the defined purpose.

void prn(int n) {
	int i;
	for(i = 1;i <= n; i++) {
		printf("Hello");
	}
}

Similarly, the above code snippet wants to print "Hello" for n times, so variable "n" becomes the input for this function but doesn't return any value.

Now it is clear that always two-way communication is not required while creating a function.

So Now how a user should decide a function should receive input and return value or any of them.

The key concept for creating a function is summarized in a few points listed below...

  1. A function is a modular programming approach.
  2. A module is best used if it performs only a defined task. For example, the first code snippet for sum() function only performs a total of two numbers. No input is performed by the function and no output is performed by the function so to perform a total of 2 numbers this function is best suitable in comparison to the other two sum() functions defined by other two code snippets. 

Function calls

In C, function calls can be of two types...

  1. Call by value
  2. Call by reference

Call by value

In this type of function call a copy of the actual argument is passed to formal arguments and if formal arguments(copy) are changed the original variable remains unchanged.

The following examples demonstrate, how call by value works?

Program to swap two numbers

#include<stdio.h>
void swap(int x,int y) {
	int t;
	t = x;
	x = y;
	y = t;
	
	printf("x = %d y = %d\n",x,y);
}

int main() {
	int a,b;
	
	printf("Enter any two numbers: ");
	scanf("%d%d",&a,&b);
	
	swap(a,b);
	
	printf("a = %d b = %d",a,b);
	return 0;
}

Output

Enter any two numbers: 5 6
x = 6 y = 5
a = 5 b = 6

Explanation

  1. As you can see in the above example, the value of the actual argument is 5 and 6 that is input by the user.
  2. When we call swap function with a,b then the value of a and b is copied int formal arguments x and y.
  3. In swap function value of x and y is interchanged and gets printed as shown in the output.
  4. As we come back to the main function and prints the actual argument that remains unchanged this happens because in memory actual argument and formal arguments are stored in different locations and treated different variables. so if formal argument changed then the actual argument remains unchanged.
Note: call by reference is discussed in pointers.

Functions in C part-1 | Video Tutorial in Hindi

Function in C with example part-2 | Video Tutorial in Hindi

Function in C with example part-2 | Video Tutorial in Hindi

Function in C part-3 | Video Tutorial in Hindi