In function prototypes and function calls, variables and values are enclosed within parentheses.
These are categorized into two groups: formal parameters and actual parameters.
In this article, we will learn about them in detail.
Parameters: Definition
A parameter is a variable that is used to pass data to a function when it is called. Parameters are defined in the function’s definition, and they are used to represent the input that the function needs to perform its task.
To learn more about passing parameters to functions, you can refer to our guide on Passing Arguments to Functions in C++.
Formal Parameters
Formal parameters, also known as function parameters, are the variables that are declared in the function definition. They are used to hold the actual parameters that are passed to the function when it is called.
For example,
void add(int a, int b) { int sum = a + b; // ... }
In the above example, x
and y
are the formal parameters. When the add()
function is called, the actual parameters are passed to the function and assigned to the formal parameters.
Actual Parameters
Actual parameters, also known as function arguments, are the values that are passed to a function when it is called. They are enclosed in parentheses after the function name.
For example,
int main() { int num1 = 10; int num2 = 20; // Pass the actual parameters num1 and num2 to the add() function. int sum = add(num1, num2); // ... }
In the above example,
num1
and num2
are the actual parameters. They are passed to the add()
function when it is called in the main()
function.
Example: A C++ Program To Demonstrate The Concept of Formal and Actual Parameters
#include <iostream> using namespace std; // Function definition void add(int a, int b) { // Calculate the sum of a and b. int sum = a + b; // Print the sum. cout << "The sum of " << a << " and " << b << " is " << sum << endl; } int main() { // Declare two variables to store the actual parameters. int x = 5; int y = 10; // Call the add() function and pass the actual parameters x and y. add(x, y); return 0; }
OUTPUT OF THE PROGRAM
The sum of 5 and 10 is 15
In the above example program,
We have defined the add()
function with two formal parameters, a
and b
. These parameters are declared in the function definition:
void add(int a, int b)
The actual parameters are passed to the add()
function when it is called from the main()
function:
add(x, y);
The values of the actual parameters, x
and y
, are assigned to the formal parameters, a
and b
, respectively.
The add()
function then calculates the sum of a
and b
and prints the result to the console.
Note: Formal parameters are always variables, but actual parameters may not be variables. Numbers, expressions, or even function calls can also be used as actual parameters.