Junior — Middle
How can a variable be passed to a function in C++: by value, by reference, or by pointer?
sobes.tech AI
Answer from AI
In C++, a variable can be passed to a function in three main ways:
- By value — the function receives a copy of the variable. Changes inside the function do not affect the original.
void foo(int x) {
x = 10; // change to local copy
}
- By reference — the function receives a reference to the original variable. Changes inside the function affect the original variable.
void foo(int& x) {
x = 10; // will change the original
}
- By pointer — the function receives the address of the variable. To access the value, dereference the pointer. Allows passing nullptr and modifying the original.
void foo(int* x) {
if (x != nullptr) {
*x = 10; // will change the original
}
}
The choice of method depends on the task: if you need to modify the original variable — it's better to use a reference or a pointer; if not — pass by value.