Can someone explain the difference between pass by reference and pass by value?

closed account (EApGNwbp)
Pass By Reference VS Pass By Value in C++

can we use both in return type functions ex int and void?

I am so confused any help would help tremendously!
thanks!
When you pass something by reference - functionName(int& variableName) - whenever you alter the value of variableName within that function, it modifies the value of the original variable that you passed it, outside of that function. Pass by value basically creates a local variable that only has scope within the range of that function. In essence, it creates a copy of the original, instead of a reference.


Exmaple:
1
2
3
4
5
6
7
8
9
10

void getReference(int& variableName){
    variableName = 2;
}

int main (){
    int variableName = 1;
    getReference(variableName);
    cout << variableName << endl;
}


Would produce (output) - 2. This is because you altered the original value of variableName once in main, then called getReference, passing the variable to it by reference and then altering it in that function, thereby altering it's original value in main().

Notice the parameter in the function getReference includes the & symbol. this allows you to pass whatever variable after it as a reference.
Last edited on
The return type makes no difference from a technical perspective, though it will be part of the choices made in the design of the function.
Tutorial: http://www.cplusplus.com/doc/tutorial/functions2/
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!
Last edited on
Topic archived. No new replies allowed.