In this tutorial, you will get familiarise to functions in c and types of functions used in programming.
A function is defined as a group of code or statements that performs a specific task.
Let us consider, you have to create a program to add to numbers. So depending upon numbers from the user. You can create two functions to solve this problem:
- create an addition function
- display function( to display the result)
So we are dividing complex problem into small divisions which makes program easy to understand and use by creating functions.
Types of functions in C programming
There are two types of functions in C programming depending on whether a function is defined by the user or already included in C compilers:
- Predefined functions
- User-defined functions
Predefined Functions
The predefined functions are built-in functions in C language. They are used to handle the tasks such as mathematical and logical calculations, I/O processing etc.
Predefined functions are defined in the header file. When you include the header file, these functions are available for use.
For example:
The printf() is a standard library function defined in “stdio.h” header file. This function is used to send compiled output to the console ( output screen).
There are other numerous library functions defined under “stdio.h”, such as scanf(), fprintf(), getchar() etc.
User-defined functions
C language allow programmers to define function . Such functions which are created by the user are called user-defined functions.
Depending upon requirements of the program, you can create as many user-defined functions as you want.
Defining a Function
Syntax :−
return_type function_name( parameter list ) { body of the function }
# Return Type − The return_type
is the data type of the value the function returns.
For example:
int add();
int is a return type in the above statement i.e. function add will return an integer value.
Some functions performs their desired task without returning any value. In this case, the return_type of the function is the keyword void.
- Function Name− this is a genuine label (name) of the function. The function name and the parameter list together constitute the function’s name.
- Parameters− A parameter is list of variables. When a function is called, you pass a value to the parameter.
This value is also referred to as an argument. The parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional, i.e. there may be a function which contain no parameters.
- Function Body− The function body contains a collection of statements that define operations performed under the function.
Advantages of using function:
- Program will be easier to understand, maintain and debug.
- Re-usability of code increases.
- A large/complex program can be divided into smaller division. Hence it would be easier to solve a complex problem in optimised way.
If you have any doubt please comment below.