C Functions


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

Code optimization

It makes the code optimized, we don't need to write much code.


The declare function

return_type function_name(data_type parameter...){  
//code to be executed  
} 

All the parts of a function

  • Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
  • Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.
  • Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
  • Function Body: The function body contains a collection of statements that define what the function does.

The call function

variable=function_name(arguments...);  
  • variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.
  • function_name: The function_name is name of the function to be called.
  • arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.

Example

#include <stdio.h>      
#include <conio.h>    
//defining function    
int cube(int n){  
return n*n*n;  
}  
void main(){      
int result1=0,result2=0;    
clrscr();      
  
result1=cube(2);//calling function  
result2=cube(5);    
      
printf("%d \n",result1);  
printf("%d \n",result2);  
  
getch();      
}      
Output
8
125

Function Arguments

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

There are two ways that arguments can be passed to a function.

Call TypeDescription
Call by valueThis method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Call by referenceThis method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

Share this article on