About C function with parameter
In C programming, a function can be declared with parameters. Parameters are used to pass data inside the function.
A function may have single or multiple parameters of different data types though it can be declared without parameter.
Parametrs are placed inside the parentheses '()' of the function. Each parameters are seperated by comma (,).
Data type of parameter must be declared at the time of function declaration and definition.
Please note that the data types of the arguments passed to a function must match the data types of the parameters specified in the function declaration and definition.
Create and call a function with parameters
A function with parameters will be created and called in the following examples:
Example of defining a function with parameter
xxxxxxxxxx
#include <stdio.h>
// defining the function with two int parameters
int addNumber(int a, int b) {
return a + b;
}
int main() {
//function will be called here
return 0;
}
Explanation of code:
-
int addNumber(int a, int b)
: The line defines a function named 'addNumber' with two integer parameters 'int a' and 'int b'.int
is the data type of parameters anda
andb
are names of parameters. -
return a + b;
: The function operates on the parameters by adding their values. This returns the sum of values of two parameters 'a' and 'b'. The result will be of an integer type.
Example of calling a function with parameters
xxxxxxxxxx
#include <stdio.h>
// defining the function with two int parameters
int addNumber(int a, int b) {
return a + b;
}
int main() {
int sum = addNumber(7, 4); //function called with arguments 7 and 4
printf("%d", sum);
return 0;
}
Output of the above example
11
Explanation of code:
-
int sum = addNumber(7, 4);
: The code 'addNumber(7, 4)' calls the 'addNumber' function passing two integer arguments 7 and 4 that match the data types of parameters. The returned result is assigned to an integer variable 'sum'. Please note that two integer numbers are passed as function arguments. -
printf("%d", sum);
: The line prints the value of 'sum' variable. The '%d' is the format specifier for integer data in C program.
Example of calling a function passing variables as arguments
xxxxxxxxxx
#include <stdio.h>
// defining the function with two int parameters
int addNumber(int a, int b) {
return a + b;
}
int main() {
int num1 = 10; // variable
int num2 = 15; // variable
int sum = addNumber(num1, num2); //function called
printf("The sum is %d", sum);
return 0;
}
Output of the above example
The sum is 25
Explanation of code:
-
int sum = addNumber(num1, num2);
: The code 'addNumber(num1, num2)' calls the 'addNumber' function passing two integer variables 'num1' and 'num2' that match the data types of parameters. The return result is assigned to an integer variable 'sum'. Please note that two integer variables are passed as function arguments. -
printf("The sum is %d", sum);
: The line prints the value of 'sum' variable.