Types of User-defined function

There are 4 different types of user-defined functions, they are

  • Function with no arguments and no return value
  • Function with no arguments and a return value
  • Function with arguments and no return value
  • Function with arguments and a return value

Function with no arguments and no return value

This type of functions does not receive any parameters as arguments as well as it wont return any values.
Such functions can either be used to display information or they are completely dependent on user inputs.

Below is an example of a function, which takes 2 numbers as input from user, and display which is the greater number.

Example

#include<stdio.h>

void multiple();       // function declaration

int main()
{
    multiple();        // function call
    return 0;
}

void multiple()        // function definition
{
    int a, b;
    printf("Enter 2 numbers to perform multiplication");
    scanf("%d%d", &a, &b);
	printf("Result is %d",(a*b));
}

Function with no arguments and a return value

This type of model will taken no inputs as argument but returns a value.

We have modified the above example to make the function multiple() return the number which is greater amongst the 2 input numbers.

Example

#include<stdio.h>
// function declaration
int multiple();       

int main()
{
	int result;
	// function call
    result = multiple();        
	printf("Result is %d",result);
    return 0;
}
// function definition
int multiple()        
{
    int a, b;
    printf("Enter 2 numbers to perform multiplication");
    scanf("%d%d", &a, &b);
	return (a*b);
}

Function with arguments and no return value

This model takes input as arguments and it does not returns a value.

This time, we have modified the above example to make the function multiple() take two int values as arguments, but it will not be returning anything.

Example

#include<stdio.h>
// function declaration
void multiple(int a, int b);       

int main()
{
    int a, b;
    printf("Enter 2 numbers to perform multiplication");
    scanf("%d%d", &a, &b);

	// function call
	multiple(a,b);
    return 0;
}
// function definition
void multiple(int a, int b)        
{
	int result;
    result = a*b;        
	printf("Result is %d",result);
}

Function with arguments and a return value

This model takes input as arguments and returns a value.

This is the recommended way, as the function is completely independent of inputs and outputs, and only the logic is defined inside the function body.

Example

#include<stdio.h>
// function declaration
int multiple(int a, int b);       

int main()
{
    int a, b, result;
    printf("Enter 2 numbers to perform multiplication");
    scanf("%d%d", &a, &b);
	// function call
	result = multiple(a,b);
	printf("Result is %d",result);
    return 0;
}
// function definition
int multiple(int a, int b)        
{
	return a*b;
}

Most Read