A function is a block of code that performs a specific task. It is a set of statements that take inputs, do some specific computation and produces output. A function can be called multiple times to provide reusability and modularity to the C program.
Example :
#include <stdio.h>
void functionName()
{
... .. ...
}
int main()
{
... .. ...
functionName();
... .. ...
}
Advantage of functions in C :
There are the following advantages of C functions.
- Reusability is the main achievement of C functions.
- Functions help us in reducing code redundancy.
- Functions make code modular.
- Functions provide abstraction.
- Debugging of the code would be easier if you use functions, as errors are easy to be traced.
However, Function calling is always a overhead in a C program.
Types of functions in C:
- Predefined standard library functions :
Standard library functions are also known as built-in functions. These functions are already defined in header files (files with .h extensions are called header files such as stdio.h). Functions such as puts(), gets(), printf(), scanf() etc are standard library functions. printf() function is defined inheader file. - User Defined functions :
These functions are created by the C programmer, so that he/she can use it many times. It reduces the complexity of a big program and optimizes the code.
Syntax of a user defined function :
return_type function_name (argument list)
{
// code of this function
}
- return_type: Return type can be of any data type such as int, double, char, void, short etc.
- function_name: It can be anything, but should be meaning and relevant name.
- argument list: Argument list contains variables names along with their data types.
- code of this function: Set of C statements which perform required task in function.
A function may or may not accept any argument. It may or may not return any value.
- function without arguments and without return value
- function without arguments and with return value
- function with arguments and without return value
- function with arguments and with return value
Notes :
- C uses call by value parameter passing technique.
- main() in C program is also a function.
- A C program can have any number of functions.
- A function can call itself and it is known as “Recursion”.
Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.
