Зміст курсу
C++ Functions
C++ Functions
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).
main
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.
main
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 *
operator).
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).
main
Conclusion
Все було зрозуміло?