In C++, functions can be used to pass data by reference, allowing the function to modify the actual argument passed. This is in contrast to passing by value, where a copy of the argument is made.
When passing by reference, the function works with the original variable, so any changes made inside the function are reflected outside the function as well. This is achieved using reference parameters in the function definition.
To define a function with reference parameters, use the ampersand (&) after the data type in the parameter list. Here’s an example:
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
In this example, the swap function takes two reference parameters, a and b. When called, it swaps the values of the two variables passed to it.
To call a function with reference parameters, simply pass the variables as you would for a normal function:
int main() {
int x = 10;
int y = 20;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swap(x, y);
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
In this example, the main function calls swap with x and y. Before the call, x is 10 and y is 20. After the call, x is 20 and y is 10.
Reference parameters are similar to pointer parameters but have some key differences:
swap(int &a, int &b)
that takes two integers
by reference and swaps their values.
swap()
function, which takes two integers by
reference.main()
, ask the user for two numbers, call the
swap()
function, and display the swapped values.
calculate(int a, int b, int &sum, int &product)
that takes two
integers by value and returns their sum and product using reference
parameters.
sum
and product
by reference to store the
results.main()
, display the sum and product of the two numbers.
findMax(int &a, int &b, int &c)
that takes
three integers by reference and finds the maximum value among them.
max
and print the result.
area
and circumference
by reference.
main()
.processString(string &input, int &length, int &sum)
that
calculates the length of the string and the sum of the ASCII values of all
characters in the string using reference parameters.
main()
.main
function.viscDen()
that
returns the viscosity and
density of the selected fluid by using reference parameters. The type of
fluid should be input to
the function as a character that’s passed by value.