Function Parameters
A parameter or an argument of a function is the information we wish to pass to the function when it is called to be executed. Parameters act as variables inside the function.
Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
Here’s the basic syntax of a function
return_type functionName(parameter1, parameter2) {
// body of the function
}
What is the return_type?
Return type specifies the data type the function should return after its execution. It could also be a void where the function is required to return nothing.
Different ways to define a function
-
Without arguments and without return value
In this function, we don’t have to give any value to the function (argument/parameters) and even don’t have to take any value from it in return.
One example of such functions could be:
#include <stdio.h> void func() { printf("This function doesn't return anything."); } int main() { func(); }
Output:
This function doesn’t return anything.
-
Without arguments and with the return value.
In these types of functions, we don’t have to give any value or argument to the function but in return, we get something from it i.e. some value.
One example of such functions could be:
#include <stdio.h> int func() { int a, b; scanf("%d", &a); scanf("%d", &b); return a + b; } int main() { int ans = func(); printf("%d", ans); }
Input:
5 6
Output:
11
The function
func
when called, asks for two integer inputs and returns the sum of them. The function’s return type is an integer. -
With arguments and without a return value.
In this type of function, we give arguments or parameters to the function but we don’t get any value from it in return.
One example of such functions could be:
#include <stdio.h> void func(int a, int b) { printf("%d", a * b); } int main() { func(2, 3); }
Output:
6
The function’s return type is void. And it takes two integers as its parameters and prints the product of them while returning nothing.
-
With arguments and with the return value
In these functions, we give arguments to a function and in return, we also get some value from it.
One example of such functions could be:
#include <stdio.h> int func(int a, int b) { return a + b; } int main() { int ans = func(2, 3); printf("%d", ans); }
Output:
5
The function
func
takes two integers as its parameters and returns an integer which is their sum.
Make sure the return statement and the return_type of the functions are the same.