Search code examples
c++cmemory-efficient

Why does C not have pass by address/reference without pointers?


Consider the trivial test of this swap function in C++ which uses pass by pointer.

#include <iostream>

using std::cout;
using std::endl;

void swap_ints(int *a, int *b)
{
   int temp = *a;
   *a = *b;
   *b = temp;
   return;
}

int main(void)
{
   int a = 1;
   int b = 0;
   cout << "a = " << a << "\t" << "b = " << b << "\n\n";
   swap_ints(&a, &b);
   cout << "a = " << a << "\t" << "b = " << b << endl;

   return 0;
}

Does this program use more memory than if I had passed by address? Such as in this function decleration:

void swap_ints(int &a, int &b)
{
   int temp = a;
   a = b;
   b = temp;
   return;
}

Does this pass-by-reference version of the C++ function use less memory, by not needing to create the pointer variables?

And does C not have this "pass-by-reference" ability the same that C++ does? If so, then why not, because it means more memory efficient code right? If not, what is the pitfall behind this that C does not adopt this ability. I suppose what I am not consider is the fact that C++ probably creates pointers to achieve this functionality behind the scenes. Is this what the compiler actually does -- and so C++ really does not have any true advantage besides neater code?


Solution

  • The only way to be sure would be to examine the code the compiler generated for each and compare the two to see what you get.

    That said, I'd be a bit surprised to see a real difference (at least when optimization was enabled), at least for a reasonably mainstream compiler. You might see a difference for a compiler on some really tiny embedded system that hasn't been updated in the last decade or so, but even there it's honestly pretty unlikely.

    I should also add that in most cases I'd expect to see code for such a trivial function generated inline, so there was on function call or parameter passing involved at all. In a typical case, it's likely to come down to nothing more than a couple of loads and stores.