Types of Functions in C
Types of Functions in C
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);
}
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: 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:
#include <stdio.h>
void main()
{
int sub(int,int); //function with return value and arguments
int 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
}
#include <stdio.h>
int main()
{
void sum(float,float); //function with arguments and no return value
float 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);
}
3. Functions without arguments and with return values
#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);
}
4. Functions without arguments and without return values
#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);
}