Tackling your separately, the 'point' of a void function could be many things. Maybe an output function that output's to the screen or a file. Also, some things, like arrays can't be returned via the
return
statement. (Though arrays are special cases.)
As far as passing-by-reference goes...
There a two ways of passing values to a function, "pass by reference" and "pass by value".
Pass-by-value is a one-way trip into your function. You can take that value, do whatever you want with it, and that value stays inside your function.
When you pass a variable-by-reference into your function, when that function ends, the value gets sent back to the calling function.
Here is an example of a useful pass-by-reference function: Swap:
1 2 3 4 5 6
|
void swap( int &x, int &y)
{
int tmp = x;
x = y;
y = tmp;
}
|
swap takes two integers, and with the help of a temporary int variable, swaps x and y. Then, since we are passing by reference, x and y return back to the calling function.
So here with this main calling swap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
using namespace std;
void swap( int &x, int &y)
{
int tmp = x;
x = y;
y = tmp;
}
int main() {
int val1 = 10;
int val2 = 20;
cout << val1 << " " << val2 << endl;
swap(val1, val2)
// val1 = 20 and val2 = 10
cout << val1 << " " << val2 << endl;
}
|
Your output is this: