In C++, there are two ways to pass arguments to a function: call by value and call by reference. Here’s an explanation of both:
Call by Value
In call by value, the value of the argument is passed to the function. This means that any changes made to the argument inside the function have no effect on the original value outside the function. Here’s an example:
void changeValue(int x) {
x = 5;
}
int main() {
int num = 10;
changeValue(num);
cout << num << endl; // Output: 10
return 0;
}
C++In this example, we define a function changeValue
that takes an integer argument x
. Inside the function, we assign x
the value of 5
. Then, in main
, we define an integer variable num
and assign it the value of 10
. We then call changeValue
with num
as the argument. However, when we print num
to the console, we get the value 10
, not 5
. This is because num
was passed by value, so any changes made to x
inside changeValue
have no effect on num
outside the function.
Call by Reference
In call by reference, a reference to the argument is passed to the function. This means that any changes made to the argument inside the function also affect the original value outside the function. Here’s an example:
void changeValue(int& x) {
x = 5;
}
int main() {
int num = 10;
changeValue(num);
cout << num << endl; // Output: 5
return 0;
}
C++In this example, we define a function changeValue
that takes an integer reference x
. Inside the function, we assign x
the value of 5
. Then, in main
, we define an integer variable num
and assign it the value of 10
. We then call changeValue
with num
as the argument. When we print num
to the console, we get the value 5
, not 10
. This is because num
was passed by reference, so any changes made to x
inside changeValue
also affect num
outside the function.
To summarize, call by value passes a copy of the argument to the function, while call by reference passes a reference to the argument to the function. Call by reference can be more efficient for large data types, as it avoids making a copy of the argument. However, it can also be more dangerous, as it allows the function to modify the original value outside the function.