Creating references and pointers
When writing C++ code, a variable may not be accessed in only one place. Copying variable values into multiple places brings the risk of inconsistent variable values, as well as lower performance and more memory usage.
Look at the following addition example:
float Add(float a, float b){ return a + b; } Void main() { int x = 1, y = 2; cout << Add(x, y); }
You can see that the function’s parameters actually copy the x
and y
values into the two a
and b
variables, which means that a
and b
have their own storage, and any value changes on a
and b
within the Add
function won’t affect the values of x
and y
.
Using references and pointers in C++ can not only help to use less memory and improve performance but also provide the flexibility to modify the original variable values.
References
A reference variable is a reference to an existing variable, and it is defined with the &
operator...