Quantcast
Channel: What's the difference between passing by reference vs. passing by value? - Stack Overflow
Viewing all articles
Browse latest Browse all 19

Answer by user326964 for What's the difference between passing by reference vs. passing by value?

$
0
0

Pass by value - The function copies the variable and works with a copy(so it doesn't change anything in the original variable)

Pass by reference - The function uses the original variable, if you change the variable in the other function, it changes in the original variable too.

Example(copy and use/try this yourself and see) :

#include <iostream>

using namespace std;

void funct1(int a){ //pass-by-value
    a = 6; //now "a" is 6 only in funct1, but not in main or anywhere else
}
void funct2(int &a){ //pass-by-reference
    a = 7; //now "a" is 7 both in funct2, main and everywhere else it'll be used
}

int main()
{
    int a = 5;

    funct1(a);
    cout<<endl<<"A is currently "<<a<<endl<<endl; //will output 5
    funct2(a);
    cout<<endl<<"A is currently "<<a<<endl<<endl; //will output 7

    return 0;
}

Keep it simple, peeps. Walls of text can be a bad habit.


Viewing all articles
Browse latest Browse all 19

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>