2. Function Arguments Specification
Passing Arguments by Value/Pointer/Reference
C++ offers a unique advantage by enabling direct manipulation with computer memory, providing greater flexibility in our programs. The following discussion will explore three methods of passing function arguments from a memory perspective.
Pass by value
In the previous section, we discussed variable scopes and established that variables created within a function are only accessible within that function. This concept remains true even when passing arguments to a function. Variables declared in the function signature have local scope; they are passed by value, meaning their values are copied into the function and stored in separate variables (remember our library book example to understand it).
Pass by pointer
It's not always good to pass arguments by value. Firstly, passing a copy consumes additional memory. Secondly, there are situations where it's necessary to modify the variable inside a function without relying on a return statement. In such cases, using a pointer to pass the variable is more appropriate.
Passing a variable by pointer in C++ as a function argument involves passing the memory address of the variable rather than its actual value.
Passing by pointer is done using pointers (
* operator) in function parameters.
int*type specifier inside the function signature which means the following: the
numPtrargument is the memory address of the variable with type
main()function, we use the
&numberconstruction to pass the address of the
numbervariable as the function argument.
Pass by reference
In C++, passing by reference means passing the memory address of a variable directly to a function, allowing the function to modify the original variable's value without any additional operations (like dereferencing pointer using the
Passing by reference is done using references (
& operator) in function parameters.
In general, passing by reference is very similar to passing by pointer, but there are two important differences:
- we don't need to use dereferencing (
*) inside the function when passing by reference to use the variable (as a result, we have direct access to the corresponding variable).
- we don't need to use the "address-of" operator (
&) to pass the reference of the variable as an argument of the function when calling it (but we still have to use the
&operator instead of
*in the function signature).
|Aspect||Pass by Value||Pass by Pointer||Pass by Reference|
|Memory Usage||Copies the value||Stores memory address||References original variable|
|Accessing Value||Directly accesses value||Requires dereferencing||Direct access, no dereference|
|Modification||Cannot modify original||Can modify through pointer||Can modify original directly|
Which method of passing arguments allows direct modification of the original variable inside a function?
Select the correct answer
Everything was clear?