Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Passing Arguments by Value/Pointer/Reference | Function Arguments Specification
C++ Functions
course content

Зміст курсу

C++ Functions

C++ Functions

1. Introduction
2. Function Arguments Specification
3. Function Return Values Specification
4. Some Advanced Topics

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).

cpp

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.

cpp

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).
cpp

main

Conclusion

Which method of passing arguments allows direct modification of the original variable inside a function?

Виберіть правильну відповідь

Все було зрозуміло?

Секція 2. Розділ 2
We're sorry to hear that something went wrong. What happened?
some-alt