Parameters and Arguments
When defining a function, you can specify one or more parameters. Parameters are like variables that are defined in the function's declaration and are used to pass values into the function. When calling a function, you can provide arguments which correspond to the parameters of the function.
Let's take a look at an example:
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4// Function declaration
5int add(int a, int b);
6
7int main() {
8 int num1, num2, sum;
9
10 cout << "Enter first number: ";
11 cin >> num1;
12
13 cout << "Enter second number: ";
14 cin >> num2;
15
16 // Function call
17 sum = add(num1, num2);
18
19 // Print the sum
20 cout << "Sum: " << sum << endl;
21
22 return 0;
23}
24
25// Function definition
26int add(int a, int b) {
27 return a + b;
28}
In this example:
- We declare a function
add
that takes two integer parametersa
andb
. - Inside the
main
function, we prompt the user to enter two numbers and store them innum1
andnum2
respectively. - We then call the
add
function with the argumentsnum1
andnum2
to calculate their sum. - Finally, we print the sum using the
cout
object.
You can run the above code to see it in action!
xxxxxxxxxx
28
using namespace std;
// Function declaration
int add(int a, int b);
int main() {
int num1, num2, sum;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
// Function call
sum = add(num1, num2);
// Print the sum
cout << "Sum: " << sum << endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment