Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is 'pass by reference' implemented without actually passing an address to a function? [closed]

I am well aware of the fact that in C and C++ everything is passed by value (even if that value is of reference type). I think (but I'm no expert there) the same is true for Java.

So, and that's why I include language-agnostic as a tag, in what language can I pass anything to a function without passing some value?

And if that exists, what does the mechanism look like? I thought hard about that, and I fail to come up with any mechanism that does not involve the passing of a value.

Even if the compiler optimizes in a way that I don't have a pointer/reference as a true variable in memory, it still has to calculate an address as an offset from the stack (frame) pointer - and pass that.

Anybody who could enlighten me?

like image 876
GermanNerd Avatar asked Nov 19 '25 11:11

GermanNerd


1 Answers

From C perspective:

There are no references as a language level concept. Objects are referred to by pointing at them with pointers.

The value of a pointer is the address of the pointed object. Pointers are passed by value just like any other arguments. A pointed object is conceptually passed by reference.


At least from C++ perspective:

How is 'pass by reference' implemented [...] ?

Typically, by copying the address of the object.

... without actually passing an address to a function?

If a function invocation is expanded inline, there is no need to copy the address anywhere. Same applies to pointers too, because copies may be elided due to the as-if rule.


in what language can I pass anything to a function without passing some value?

Such language would have to have significantly difference concept of a function than C. There would have to be no stack frame push.

Function-like C pre-processor macros, as their name implies, are similar to functions, but their arguments are not passed around at runtime, because pre-processing happens before compilation.

On the other hand, you can have global variables. If you change the global state of the program, and call a function with no arguments, you have conceptually "passed the new global state to the function" without having passed any value.

like image 69
eerorika Avatar answered Nov 21 '25 09:11

eerorika



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!