I would like to know if you could help me to know the idea behind pass by value and pass by reference that the compiler needs to make, what are the steps involved? I'd be really helpful if you could give me a hand on this since I'm working on a project which is a mini-compiler.

- 354,903
- 100
- 647
- 710

- 989
- 4
- 16
- 35
-
3This is a really broad, non-specific question. Something like [the dragon book](http://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools) might be a better starting point... – Matt Ball Nov 19 '11 at 23:53
2 Answers
Pass by value is the most basic form of passing. And everything is implemented in terms of pass-by-value in the end.
If you're asking about what actually happens when a function is called and arguments are passed by value, this varies by platform. Each platform has its own "calling convention". What happens most of the time, is that the first few arguments are stored in processor registers. Any remaining arguments will be stored in a pre-defined location in the called function's stack frame, similar to local variables. (How local variables are stored in a stack frame is decided by the compiler at compile time.) So when a function is called, any arguments that need to be stored on the stack are copied there; and any arguments that need to be stored in registers are loaded there. Then control is passed to the function.
As for pass-by-reference, if a language has pointers, pass by reference can be done by passing pointers by value. The compiler can just have a preprocessing step where it "eliminates" pass by reference by making the following translation:
- For every function parameter that is pass by reference, it changes it to a pointer to that type passed by value (e.g.
void func(int &foo)
->void func(int *foo)
) - For every use of that pass-by-reference parameter inside that function, change it to an explicit pointer dereference (e.g.
foo
->*foo
) (with the exception that if it is passed by reference again, don't dereference it) - Every time that function is called, whatever is passed to the pass-by-reference variable, take the address of it explicitly (e.g.
func(bar)
->func(&bar)
)

- 119,665
- 29
- 163
- 224
It depends entirely on how the compiler handles variables (what could be termed the "environment").
When variables are translated to memory references (such as in C compilers), pass-by-reference may be implemented by using pointers behind the scenes, with the compiler generating the necessary code to de-reference pointers. Pass-by-value is handled by copying data, then referring to the copy.
If the compiler uses a symbol table (which is more typical of interpreters than compilers) pass-by-value may be done by copying the existing symbol table entry to a new one for the new variable, while pass-by-reference would simply use the existing entry.
Other environments would require other approaches.

- 75,655
- 22
- 151
- 221