Parameters can be passed to functions in C++ by value, by pointer and by reference.
Normal variables, i.e. no pointer variables, are passed to the function as function parameters by value. This means that during the execution of a function a copy of the variable is created on the stack of the processor.
In C++ there is also the possibility that the parameter passing is done by pointer. In this case the addresses of the variables, and not the variable itself, are passed to the function.
C++ has introduced another form of parameter passing, the passing by reference. This is identified by the fact that the function parameter is preceded by a &, which must not be confused with the address operator & in this context.
When using C++, parameter passing by reference is always preferable to passing by pointer.
Line | Description |
---|---|
4 | Function header of the add() function with input parameters a and b of type integer |
5 | Create variable named result of type integer |
6 | Result is assigned the sum of a and b |
7 | Returns the variable result |
10 | main() function of type integer |
11 | Calls the add() function with the parameters 1 and 3 in an output stream and thus outputs the sum of the two numbers |
12 | Calls the add() function with the parameters 5 and 6 in an output stream and thus outputs the sum of the two numbers |
#include <iostream>
using namespace std;
int add(int a, int b) {
int result;
result = a + b;
return result;
}
int main() {
cout << add(1, 3) << endl;
cout << add(5, 6) << endl;
}
4
11
Line | Description |
---|---|
4 | Function header of the add() function with the input parameters pointer to a (*a ) and pointer to b (*b ) of type integer . Thus the address of the variable is accessed. |
5 | Create variable named result of type integer |
6 | Result is assigned the sum of *a and *b |
7 | Returns the variable result |
10 | main() function of type integer |
11 | Declares and initializes the variable a with the value 1, b with the value 3, and c with the value 5 |
12 | Calls the add() function with the parameters &a and &b in an output stream, thus outputting the sum of the two numbers. Due to the address operator, the memory addresses where the variable values are stored are passed |
13 | Calls the add() function with the parameters &a and &c in an output stream, thus outputting the sum of the two numbers. Due to the address operator, the memory addresses where the variable values are stored are passed |
#include <iostream>
using namespace std;
int add(int *a, int *b) {
int result;
result = *a + *b;
return result;
}
int main() {
int a = 1, b = 3, c = 5;
cout << add(&a, &b) << endl;
cout << add(&a, &c) << endl;
}
4
6
#include <iostream>
using namespace std;
int add(int &a, int &b) {
int result;
result = a + b;
return result;
}
int main() {
int a = 4, b = 6, c = 12;
cout << add(a, b) << endl;
cout << add(a, c) << endl;
}
10
16