In general, I stick with return over reference, but it depends on what you are trying to do and what objects are being passed around.
Option 1: (I usually prefer this)
1 2 3
|
int add(int a, int b) {
return a + b;
}
|
int c = add(a,b); |
Option 2: (I like this if I am passing a big struct that I don't want to copy)
1 2 3
|
void add(int a, int b, int& c) {
c = a + b;
}
|
int c;
add(a, b, c); |
Option 3: (I only use this if I am doing pointer arithmetic or (de)allocation in my function)
1 2 3
|
void add(int a, int b, int* c) {
*c = a + b;
}
|
int c;
add(a, b, &c); |
Of course there are other options (i.e. returning a reference or pointer), but that starts to get more complicated.
The big advantage of option 1 is that you can declare and write to a label in the same line, also you can chain commands togeather:
1 2 3 4
|
float c;
add(a,b,&c);
abs(&c);
sqrt(&c);
|
float c = sqrt( abs( add(a,b) ) ); |
The disadvantage of option 2 is that it isn't as clear from looking at a specific use of the function that the parameter is an output. However, in the implementation of the function, it is much easier than option 3 to use that label over and over since you don't have to constantly dereference it with the * operator.
Option 2 isn't available in C, it's a C++ speciality!