Home > Article > Backend Development > What is the difference between pointers and references in C++?
Pointers and references are both tools for dealing with memory locations, but there are differences: 1. Pointers store variable addresses, and references point directly to variables. 2. Pointers access variables indirectly and references directly access them. 3. The pointer can point to null, and the reference must point to a valid variable. 4. Using pointers to exchange variable values requires dereference, but not reference.
The difference between pointers and references in C++
Pointers and references are powerful tools for handling memory locations in C++, but There are some key differences between them.
Definition
Syntax
int *ptr;
int &ref;
Indirect access
*ptr
ref
Life cycle
nullptr
). Dereference
*ptr
Practical case: exchanging the values of two variables
The following is a practical case of exchanging the values of two integer variables using pointers and references:
Pointer:
void swapPtr(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } int main() { int a = 5, b = 10; swapPtr(&a, &b); // a 现在是 10,b 现在是 5 }
Reference:
void swapRef(int &x, int &y) { int temp = x; x = y; y = temp; } int main() { int a = 5, b = 10; swapRef(a, b); // a 现在是 10,b 现在是 5 }
Conclusion
The above is the detailed content of What is the difference between pointers and references in C++?. For more information, please follow other related articles on the PHP Chinese website!