Thursday, Aug 16th

Last update12:59:40 PM GMT

What is the difference between call-by-value and call-by-reference? Which method does C use?

Write e-mail

In the case of call-by-reference, a pointer reference to a variable is passed into a function instead of the actual value. The function's operations will effect the variable in a global as well as local sense. Call-by-value (C's method of parameter passing), by contrast, passes a copy of the variable's value into the function. Any changes to the variable made by function have only a local effect and do not alter the state of the variable passed into the function.

argaiv1770

Does C really have pass by reference?

No. 

C uses pass by value, but it can pretend doing pass by reference, by having functions that have pointer arguments and by using the & operator when calling the function. This way, the compiler will simulate this feature (like when you pass an array to a function, it actually passes a pointer instead). C does not have something like the formal pass by reference or C++ reference parameters.


How will you decide whether to use pass by reference, by pointer and by value?

The selection of the argument passing depends on the situation.

  • A function uses passed data without modifying it:
    • If the data object is small, such as a built-in data type or a small structure then pass it by value.
    • If the data object is an array, use a pointer because that is the only choice. Make the pointer a pointer to const.
    • If the data object is a good-sized structure, use a const pointer or a const reference to increase program efficiency. You save the time and space needed to copy a structure or a class design, make the pointer or reference const.
    • If the data object is a class object, use a const reference. The semantics of class design often require using a reference. The standard way to pass class object arguments is by reference.
  • A function modifies data in the calling function:
    • If the data object is a built-in data type, use a pointer. If you spot a code like fixit(&x), where x is an int, its clear that this function intends to modify x.
    • If the data object is an array, use the only choice, a pointer.
    • If the data object is a structure, use a reference or a pointer.
    • If the data object is a class object, use a reference.

Share this post



Web Hosting