In C, a function is a self-contained block of statements that can be executed whenever required in the program. This tutorial guides you on how to use functions in C.
Table of Contents
Benefits of using the function in C
- The function provides modularity.
- The function offers reusable code.
- In large programs, debugging and editing tasks are effortless with functions.
- The program can be modularized into smaller parts.
- A separate function can be developed independently according to the need.
Types of Functions in C
There are two types of functions in C:
- Built-in(Library) Functions
- The system provided these functions and stored them in the library. Therefore it is also called Library Functions. e.g.
scanf()
,printf()
,strcpy
,strlwr
,strcmp
,strlen
,strcat
, etc. - You must include the appropriate C header files to use these functions.
- The system provided these functions and stored them in the library. Therefore it is also called Library Functions. e.g.
- User Defined Functions
- These functions are defined by the user when writing the program.
Parts of Function
- Function Prototype (function declaration)
- Function Definition
- Function Call
Function Prototype
Syntax:
dataType functionName (Parameter List)
Example:
int addition();
Function Definition
Syntax:
returnType functionName(Function arguments){
//body of the function
}
Example:
int addition()
{
}
Calling a Function in C
Here is the program showing the sum of two numbers using a user-defined function:
Example:
#include<stdio.h>
/* function declaration */
int addition();
int main()
{
//local variable definition
int answer;
answer = addition(); //calling a function to get addition value.
printf("The addition of the two numbers is: %d\n",answer);
return 0;
}
//function returning the addition of two numbers
int addition()
{
int num1 = 10, num2 = 5; // local variable definition
return num1+num2;
}
Program Output:
The addition of the two numbers is: 15