-9

When I pass a variable by reference like this:

void function(int &r){
    //do something
}

int main(){
    int a = 100;

    function(a);

    return 0;
}

What actually happens ? Does r contain the address of an integer variable or something ? How does it find it ?

Colin Pitrat
  • 1,992
  • 1
  • 16
  • 28
  • 8
    *What actually really happens?* It fails to compile because there are several errors in your code. If you can't be bothered to post correct code for this simple of an example, why should anyone take the time to help you? – Praetorian Jul 24 '14 at 01:16
  • 3
    Typically the implementation will just pass a pointer behind-the-scenes, but as far as I know it's not obliged to. The compiler might also inline the function and no pointers or anything will be passed. Implementation defined etc etc. – ta.speot.is Jul 24 '14 at 01:16
  • 1
    @ta.speot.is *unspecified*, rather than *implementation-defined* – M.M Jul 24 '14 at 01:17
  • Possible duplicate of [How do I pass a variable by reference?](http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – Lakmal Vithanage Dec 06 '16 at 06:58

1 Answers1

1

Reference of your integer a will be passed as argument to your function. Now in your function, if you change the value pointed by r, it will be reflected in a as well.

So if you assign r=2 in your function and print out a in main, you will see that a has the value 2.

Your program has some syntax errors, but I can understand what you wanted to convey.

Edit:

From the user perspective, it's as if you were receiving a value in the function except that modification done to it are visible from the caller. It's also cheaper in terms of performance when passing big objects because no copy is needed.

How it works in practice is that the compiler actually pass a pointer to the function. But since the caller must have a valid object to pass to the function, a reference can't be invalid contrary to a pointer so you don't need to check for NULL values.

Colin Pitrat
  • 1,992
  • 1
  • 16
  • 28
sjaymj62
  • 386
  • 2
  • 18