Question

Possible Duplicate:
What’s the difference between passing by reference vs. passing by value?

I know that the title can represent many other answered questions, I believe that my very specific question wasn't answered in other threads (I have searched, sorry if it's a duplicate).

To business: consider the next signatures:

A:

void MyFunction(long int x);

B:

void MyFunction(long int & x);

and the next usage:

void main()
{
  short int y = 0;
  MyFunction(y);
  ...
}

My question is related to the memory consumption of the parameter in the memory stack frame of MyFunction.

  1. In case A, the parameter is passed by-value, does it mean that it will consume sizeof(short int) bytes?

  2. In case B, the parameter is passed by-reference, assuming the compiler will implement it with a pointer, does it mean it will consume sizeof(pointer_type) bytes - which is probably more than short int? (I was once told that when using a reference it might consume 64 bits anyway, depending on the platform)

Note that the function receives long int type as I would like to know if it has any effect in both cases.

And another tiny question - can anyone post an example in which the compiler will NOT implement by-reference passed parameter using a pointer?

Thanks, Asaf.

Was it helpful?

Solution

The answers necessarily depend on the compiler, architecture, the ABI etc.

In what follows, I assume that the parameters in question are actually passed on the stack and not in registers (big assumption!), and there are no aggressive optimizations.

In case A, the parameter is passed by-value, does it mean that it will consume sizeof(short int) bytes?

No, it will consume sizeof(long int) bytes since it will be widened first to match MyFunction()'s signature.

In case B, the parameter is passed by-reference, assuming the compiler will implement it with a pointer, does it mean it will consume sizeof(pointer_type) bytes

In a word, yes. You can't pass a short& where a long& is expected, so I assume you meant that you're passing a long& here.

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