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()
.
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);
}
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 parameters Always!
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.
There are 4 types of functions:
This function has arguments and returns a value:
#include <stdio.h>void main(){int sub(int,int); //function with return value and argumentsint x=10,y=7;int res = sub(x,y);printf("x-y = %d",res);}int sub(int a,int b) //function with return value and arguments{return(a-b); // return value}
This function has arguments, but it does not return a value:
#include <stdio.h>int main(){void sum(float,float); //function with arguments and no return valuefloat x=10.56,y=7.22;sum(x,y);}void sum(float a,float b) //function with arguments and no return value{float z = a+b;printf("x + y = %f",z);}
This function has no arguments, but it has a return value:
#include<stdio.h>int main(){int sum();int c = sum();printf("Sum = %d",c);}int sum() //function with no arguments and return data type{int x=10,y=20,z=5;printf("x = %d ; y = %d ; z = %d \n",x,y,z);int sum = x+y+z;return(sum);}
This function has no arguments and no return value:
#include<stdio.h>int main(){void sum();sum();}void sum() //function with no arguments and return data type{int x=15,y=35,z=5;printf("x = %d ; y = %d ; z = %d \n",x,y,z);int sum = x+y+z;printf("Sum = %d",sum);}