value passed param Vs. by

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.

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

  • 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.


    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.

    链接地址: http://www.djcxy.com/p/20622.html

    上一篇: 如果在其他函数中增加,指针不会增加

    下一篇: 值通过参数VS. 通过