Question

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?

Was it helpful?

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.

OTHER TIPS

Don't confuse counting variables in your code with counting memory used by the processor. C++ has many abstractions that hide the inner workings of the compiler in order to make things simpler and easier for a human to follow.

By design, C does not have quite as many levels of abstractions as C++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top