DEV Community

Discussion on: Passing by value, passing by reference in C

Collapse
 
tisek profile image
tisek⚓

As good and relevant as the content of this article is, and it is; there a small inaccuracy.
You might say that I am very picky, or even splitting hair here.

But, technically, there is no such thing as "passing by reference" in C, there is only "passing by value". And you say it almost clearly when you say that passing pointers is a way to simulate passing by reference. But in the end, C is really passing the value of the pointers (and these values are copied in the execution context of the function just as any other "passing by value"); it just is that you can access the pointed values that are not in the execution context of the function so neither copied as call-time, nor erased at return-time.

A good way to illustrate this would be to modify the values of pointers afters the swap has occurred and show that it does not harm the result:

void swap(int *pFirstVariable, int *pSecondVariable)
{
  int temp;

// using dereferenced pointers means the function is working with the values at the addresses that are passed in
  temp = *pFirstVariable;
  *pFirstVariable = *pSecondVariable;
  *pSecondVariable = temp;

  pFirstVariable = 42;
  pSecondVariable = 78;
}

And while this might be me being picky, it just happens to show how close to the machine C language actually is, and how, languages that actually have "passing by reference" are not doing magic, but merely mildly sophisticated syntactic sugar.

Indeed, Pascal allows to add the keyword var to a function declaration to pass by reference:

procedure swap(var x, y: integer);
var
   temp: integer;

begin
   temp := x;
   x:= y;
   y := temp;
end;

Or C++, that has the confusing & for references:

#include <iostream>

void swap(int& x, int& y) 
{ 
    int z = x; 
    x = y; 
    y = z; 
} 

int main() 
{ 
    int a = 11, b = 22; 
    std::cout << "Before Swap\n"; 
    std::cout << "a = " << a << " b = " << b << "\n"; 

    swap(a, b); 

    std::cout << "After Swap with pass by reference\n"; 
    std::cout << "a = " << a << " b = " << b << "\n"; 
} 

In both cases, you handle the arguments directly without dereferencing them but really you are manipulating the very integers from the outside.

Collapse
 
mikkel250 profile image
mikkel250

Thanks for the clarification! I thought saying "C uses 'pass by value' to pass arguments ..." at the beginning had covered this, but I'll take a look at how it can be made more clear 🤓