C++ pass by: value, pointer, reference
There are different ways to pass arguments to functions in C++: by value, by pointer, and by reference. These techniques control how arguments are passed to functions, and each has its own specific use cases and effects on the original variables.
Pass by Value
When you pass an argument by value, a copy of the argument's value is made and passed to the function. Any changes made to the parameter inside the function do not affect the original variable.
void passByValue(int val) {
val++;
}
int main() {
int val = 0;
passByValue(val);
cout << "Pass by value, original val remains at " << val << endl;
return 0;
}
Output:
Pass by value, original val remains at 0
Pass by Pointer
When you pass an argument by pointer, you pass the address of the variable. This allows the function to modify the original variable's value.
void passByPointer(int* val) {
(*val)++;
}
int main() {
int val = 0;
passByPointer(&val);
cout << "Pass by pointer, original val increases to " << val << endl;
return 0;
}
Output:
Pass by pointer, original val increases to 1
Pass by Reference
When you pass an argument by reference, you pass the variable itself. This allows the function to modify the original variable directly, without the need for dereferencing pointers.
void passByReference(int& val) {
val++;
}
int main() {
int val = 0;
passByReference(val);
cout << "Pass by reference, original val increases to " << val << endl;
return 0;
}
Output:
Pass by reference, original val increases to 1