In C programming, what is the difference between call by value and call by reference? What does it mean?
call by reference means passing in a pointer. this means the called function can make changes to the "pointed to" value (unless it is declared as "const"). a parameter passed by reference will occupy the space required to hold a pointer value on the stack. call by value means passing in an entire copy of the variable. this can me it occupies more space on the stack depending on what the variable represents (e.g. if it is a "struct" it will pass in an entire copy of the "struct"). any changes made to the variable by the "called" function will only affect the copy on the stack, so the original variable remains intact.
Additionally, consider that when passing by value, creating a copy can be expensive. It's not a big deal for intrinsic types (int, float, etc.), but what if you were to pass an entire class instance by value? Not only can that lead to a large stack allocation, it'll also call the copy constructor of that class, which could be devastating to performance. Think passing a container (like a std::vector) by value - the entire container would have to be copied, including every element in it! An interesting note: while the underlying assembly a reference generates is very similar (often even identical) to a pointer, the concept isn't. For example, a reference parameter should, under normal circumstances, not be 0 (point to an invalid address). Return by reference is a different beast. Consider the following code: MyClass &GetReference() { MyClass inst; return inst; } We're returning a reference to a temporary; inst will be destroyed out of scope of GetReference(), so the reference we're returning is in fact invalid. Most compilers will barf up a warning in a case like this, but it's a good thing to be aware of.
A reference is different than passing a pointer to a variable because, to the receiving function, the reference *always* points to a valid variable. Before references, a lot of bugs were caused by NULL pointers passed to functions. The language and the compiler require that references always be initialized with a pointer to a variable, so they cannot be NULL ever. Eliminates a whole *family* of possible bugs. References are great!
Join our real-time social learning platform and learn together with your friends!