Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call by reference in C++

What is actually passed in call by reference to a function?

void foo(int &a,int &b)

when I write

foo(p,q)

what is actually passed to the function. Is it the address of p and q?

like image 383
Bruce Avatar asked Jan 27 '26 21:01

Bruce


2 Answers

What's actually passed to the function is a reference. The named parameter b becomes a synonym for the argument object q.

How the compiler probably implements this that the caller places the address of q on the stack or in a register before calling, and the callee uses that value to effect all accesses to b. But it could be misleading to describe that as "actually passing" a pointer, because parameter passing is a concept at the level of the C++ language, and at that level it is not the same concept as passing a pointer. For instance, when you pass a pointer you can pass a null pointer, but when you pass a reference you cannot (validly). So it'd be wrong to say they're same thing.

That said, the person implementing the compiler might describe it as "actually passing a pointer", and you know what they mean. For comparison, if char variables occupy 4-byte stack slots in the calling convention, they might say that the compiler is "actually passing an int". So it depends what "actually" is supposed to mean.

like image 104
Steve Jessop Avatar answered Jan 29 '26 11:01

Steve Jessop


The other answers mention the semantic difference between a reference and a pointer.

In practice, every single compiler I've ever worked with implements them the same way -- passing a reference is really passing a pointer at the assembly level. This isn't specified in any standard, it's just the case in practice everywhere.

The question's come up on SO before: What's the low-level difference between a pointer an a reference?

like image 31
Crashworks Avatar answered Jan 29 '26 10:01

Crashworks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!