English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn to pass pointers as parameters to functions and use them effectively in programs.
InC ++FunctionIn this article, you learned about passing parameters to functions. Because actual values are passed, this method is called passing by value.
However, there is another way to pass parameters to a function, in which the actual value of the parameters is not passed. Instead, only the reference to the value is passed.
#include <iostream> using namespace std; // Function prototype void swap(int&, int&); int main() { int a = 11, b = 22; cout << "Before swap" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; swap(a, b); cout << "\nAfter swap" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; return 0; } void swap(int& n1, int& n2) { int temp; temp = n1; n1 = n2; n2 = temp; }
Output result
Before swap a = 11 b = 22 After swap a = 22 b = 11
In the main() function, two integer variables a and b are defined. These integers are passed to the swap() function by reference.
The compiler can identify that this is passed by reference because the function definition is void swap(int& n1, int& n2) (Please note the data type after&symbol).
In the swap() function, only the references (addresses) of variables a and b are received, and the swap occurs at the original address of the variables.
In the swap() function, n1and n2is the formal parameter, which is actually the same as the variables a and b.
There is another way to usePointerMethods to complete the same task.
#include <iostream> using namespace std; // Function prototype void swap(int*, int*); int main() { int a = 1, b = 2; cout << "Before swap" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; swap(&a, &b); cout << "\nAfter swap" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; return 0; } void swap(int* n1, int* n2) { int temp; temp = *n1; *n1 = *n2; *n2 = temp; }
The output of this example is the same as the previous output result.
In this case, the address of the variable is passed during the function call, rather than the variable itself.
swap(&a, &b); // &a is the address of a, &b is the address of b
Since addresses are passed rather than values, the dereference operator must be used to access the value stored at the address.
void swap(int* n1, int* n2) { ... .. ... }
* n1and* n2are respectively given the values stored at the address n1and n2is the value at
because of n1which contains the address of a, so that when* n1Anything done will also change the value of a in the main() function. Similarly, b will have the value of* n2The same value.