A function is a block of statements that can perform a particular task.As we all know, there is always at least one function in C, and that is main()
.
Example
In the example below, the function’s name is sum
and the data type is int
. This task of this function is to produce the sum of two numbers:
int sum(int a,int b){ return(a+b);}
Below, the function is declared in main()
:
void main(){ int sum(int,int); //function declaration int x=5,y=6; total = sum(x,y);}
Formal parameters and actual parameters
When we call a function in main()
or anywhere else in the program, and the function we created needs parameters, we would pass parameters to it while calling the function. In the example above, we passed variables x
and y
to obtain the sum of x
and y
.
According to the example above, the formal parameters are a
and b
, and the *actual *parameters are x
and y
.
Essentially, the variables being passed in the function call are actual parameters, and the variables being initialized and used in the function are formal* *parameters.
Note: Number of formal parameters = Number of actual parametersAlways!
Advantages of a function
A function can be used any number of times after it is defined once.
Functions make programs manageable and easy to understand.
Note: After termination of the function, the program control goes back to
main()
to execute any left out statements.
Function categories
There are 4 types of functions:
1. Functions with arguments and return values
This function has arguments and returns a value: