Home > Article > Backend Development > Common errors in reference and pointer parameters in C++ functions
Common mistakes between reference parameters and pointer parameters are: reference parameters must be initialized to valid variables and cannot be changed in type, and pointer parameters must point to valid variables and cannot be released repeatedly. Additionally, pointer parameters can access uninitialized pointers and dereference unpointed variables, while reference parameters cannot point to temporary variables.
A reference parameter is like an ordinary variable, but it is an alias for another variable. This means that any modifications to the reference parameter will be reflected in the variable it refers to.
Syntax:
void function(T& reference_parameter);
int
parameter to a reference float
parameter. Pointer parameters point to the memory address of another variable. Through a pointer, the variable pointed to can be modified.
Syntax:
void function(T* pointer_parameter);
The following example demonstrates the correct usage of reference parameters and pointer parameters:
#include <iostream> void swap(int& a, int& b) { int temp = a; a = b; b = temp; } void swapPointers(int* a, int* b) { int* temp = a; a = b; b = temp; } int main() { int x = 10; int y = 20; // 调用引用参数函数 swap(x, y); std::cout << "x: " << x << ", y: " << y << std::endl; // 输出:x: 20, y: 10 int* px = &x; int* py = &y; // 调用指针参数函数 swapPointers(px, py); std::cout << "*px: " << *px << ", *py: " << *py << std::endl; // 输出:*px: 20, *py: 10 }
In this example:
function uses reference parameters and correctly swaps the values of
x and
y. The
function uses pointer parameters and correctly swaps the values of the variables pointed to by
px and
py.
The above is the detailed content of Common errors in reference and pointer parameters in C++ functions. For more information, please follow other related articles on the PHP Chinese website!